使用 x:static 在 XAML 中绑定命令

Command binding in XAML using x:static

我正在尝试在 XAML 中为静态 class 中的静态函数创建 CommandBinding。编译器 (VS) 不会接受但会说 The member "CloseCanExecute" is not recognized or is not accessible. 但是使用私有非静态成员是被接受的,我也可以访问静态字符串(见按钮)。

我做错了什么?

这是XAML

<Window x:Class="tt_WPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:tt_WPF"
    Title="MainWindow" SizeToContent="WidthAndHeight">
<Window.CommandBindings>
    <!-- THIS WILL NOT COMPILE -->
    <CommandBinding Command="Close" 
    Executed="{x:Static local:XXX.CloseExecuted}" />
    <!-- THIS IS WORKING
    <CommandBinding Command="Close" 
    Executed="CloseExecuted" />
    -->
</Window.CommandBindings>
<Button  Content="{x:Static local:XXX.SomeStaticString}" />
</Window>

下面是代码:

public static class XXX
{
    public static string SomeStaticString = "Hello World";
    public static void CloseExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("Hey, I'm closing.");
    }
}

public partial class MainWindow : Window
{
    private void CloseExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("Hey, I'm closing.");
    }

    public MainWindow()
    {
        InitializeComponent();
    }
}

总而言之,您无法通过 XAML 中的 x:Static 绑定到静态处理程序但你绝对可以从代码背后做到这一点。

在 window 加载事件或从 window 构造函数中,您可以添加与静态处理程序的命令绑定。

this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, 
                                            XXX.CloseExecuted));