How can I send multiple parameters from Button
in WPF
? I am able to send single parameter which is value of TextBox
properly. Here is the code.
XAML
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="133,22,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<Button Content="Button" Grid.Row="1" Height="23" Command="{Binding Path=CommandClick}" CommandParameter="{Binding Text,ElementName=textBox1}" HorizontalAlignment="Left" Margin="133,62,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
Code behind
public ICommand CommandClick { get; set; }
this.CommandClick = new DelegateCommand<object>(AddAccount);
private void AddAccount(object obj)
{
//custom logic
}
Passing a parameter to the CanExecute and Execute methods A parameter can be passed through the "CommandParameter" property. Once the button is clicked the selected address value is passed to the ICommand. Execute method. The CommandParameter is sent to both CanExecute and Execute events.
The RelayCommand and RelayCommand<T> are ICommand implementations that can expose a method or delegate to the view. These types act as a way to bind commands between the viewmodel and UI elements.
The ViewModel contains code associated with that ICommand property that is executed when the button is clicked. You can set CommandParameter to arbitrary data to distinguish between multiple buttons if they are all bound to the same ICommand property in the ViewModel.
Other than using the approach of defining properties in you class (let's call it your ViewModel) to be binded by your view, there are times (not common) where we don't wan't to do so, an important tool to know in these situations is the MultiBinding, so just for completeness sake , even though you are satisfied with the first option, I'll cover another approach.
so to answer your question:
1. MVVM Approach :
Use the MVVM approach and define properties to binded by your view, and use those properties in your ViewModel's command without the need for CommandParameters.
2. MultiBinding : (Can live happily with MVVM approach)
Passing the Command Parameter as a Multi Binded parameter as seen here:
<Button Content="MultiBindingExample" Command="{Binding MyCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource MyMultiConverter}">
<Binding Path="..." ElementName="MyTextBox"/>
<Binding Path="..." ElementName="MySomethingElse"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
With your Converter Defined using the IMultiValueConverter
Interface:
public class MyMultiConverter: IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
}
and for extracting the values:
Simply refer to the parameter in your command as an Object[]
and use the parameters in the same order as in the MultiBinding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With