Multiple command parameters wpf button object

戏子无情 提交于 2019-12-03 10:09:35

How can i send multiple parameters from button in wpf.

You can only send one parameter as the CommandParameter.

A better solution is typically to just bind the TextBox and other controls to multiple properties in your ViewModel. The command would then have access to all of those properties (since it's in the same class), with no need for a command parameter at all.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!