I have a command that binds to a menu item I have, I would like to pass more than one parameter. I have tried using a converter however it seems to return nothing.
My converter
public class AddConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return values.Clone();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
My View model containing my command
class myViewModel: ViewModelBase {
private RelayCommand testCommand;
public ICommand TestCommand {
get {
if (testCommand == null) {
testCommand = new RelayCommand((param) => test((object[])param));
}
return testCommand ;
}
}
//Only trying to print out one of the params as a test
public void test(object parameter) {
var values = (object[])parameter;
int num1 = Convert.ToInt32((string)values[0]);
MessageBox.Show(num1.ToString());
}
My binding on my menu item
//Using tags as a test
<ContextMenu>
<MenuItem Name="testing" Header="Move to Position 10" Command="{Binding TestCommand}" Tag="7">
<MenuItem.CommandParameter>
<MultiBinding Converter="{StaticResource AddConverter}">
<Binding ElementName="testing" Path="Tag"/>
<Binding ElementName="testing" Path="Tag"/>
</MultiBinding>
</MenuItem.CommandParameter>
</MenuItem>
</ContextMenu>
After debugging, when I open my window containing the menu item, the converter fires off, the values object is null at that point. Then, when I select my menu item and fire off the command, when I get to my execution, the parameter is null. I don't understand why my converter fires off before I even click the menu item, or why the values are null.
Try to replace the ElementName
of the bindings with a RelativeSource
. This works for me:
<MenuItem Name="testing" Header="Move to Position 10" Command="{Binding TestCommand}" Tag="7">
<MenuItem.CommandParameter>
<MultiBinding Converter="{StaticResource AddConverter}">
<Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>
</MultiBinding>
</MenuItem.CommandParameter>
</MenuItem>
Also note that you should bind to the T estCommand property and not to the testCommand
field.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.