带参数的RoutedCommand

pgu*_*icz 2 c# wpf routed-commands c#-4.0

我正在玩RoutedCommand,我遇到了一个问题,我找到了如何传递一个参数,以便我的Executed方法可以在e.Parameter中使用它?

我的路由命令:

public static readonly RoutedCommand Foo = new RoutedCommand();
Run Code Online (Sandbox Code Playgroud)

用法:

menuItem.Command = Commands.Foo;
Run Code Online (Sandbox Code Playgroud)

执行:

private void Foo_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            object parameter = e.Parameter; // this is always null
        }
Run Code Online (Sandbox Code Playgroud)

Rac*_*hel 8

你的参数总是null因为你从未在任何地方设置它

您可以使用该CommandParameter属性进行设置

menuItem.Command = Commands.Foo;
menuItem.CommandParameter = "Bar";
Run Code Online (Sandbox Code Playgroud)