How do I pass the information from View to ViewModel with DelegateCommand? How do I pass the information from View to ViewModel with DelegateCommand? wpf wpf

How do I pass the information from View to ViewModel with DelegateCommand?


Check out this MSDN article by Josh Smith. In it, he shows a variation of DelegateCommand that he calls RelayCommand, and the Execute and CanExecute delegates on RelayCommand accept a single parameter of type object.

Using RelayCommand you can pass information to the delegates via a CommandParameter:

<Button Command="{Binding SaveCommand}"         CommandParameter="{Binding SelectedItem,Element=listBox1}" />

Update

Looking at this article, it appears that there is a generic version of DelegateCommand which accepts a parameter in a similar way. You might want to try changing your SaveCommand to a DelegateCommand<MyObject> and change your Save and CanSave methods so that they take a MyObject parameter.


here is the elegant way.

Give a name to your textbox, then bind the CommandParameter in the button to it's Text property:

<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">    <TextBlock Text="{Binding FirstName}"/>    <TextBox x:Name="ParameterText" Text="Save this text to the database."/>    <Button Content="Save" Command="{Binding SaveCommand}"            CommandParameter="{Binding Text, ElementName=ParameterText}"/></StackPanel>


In your VM:

private DelegateCommand<string> _saveCmd = new DelegateCommand<string>(Save);public ICommand SaveCmd{ get{ return _saveCmd } }public void Save(string s) {...}

In you View, use CommandParameter like Matt's example.