WPF条件启用键绑定

3

我有一个WPF项目,我试图根据来自我的视图模型的公共属性状态启用/禁用键盘快捷键。也许有一个超级简单的解决方案,但我是新手WPF,我在谷歌上找不到任何东西。这是我的工作XAML:

 <KeyBinding Modifiers="Control" Key="p" Command="{Binding PrintCommand}" CommandParameter="{Binding OpenEvent}"/>

这里是我的想法:

我希望做的事情如下:

<KeyBinding Modifiers="Control" Key="p" Command="{Binding PrintCommand}" CommandParameter="{Binding OpenEvent}" IsEnabled="{Binding IsOnline}"/>

我想知道是否有类似于WPF按钮的“IsEnabled”属性的东西可以应用到这个问题上。我有大约20个不同的快捷方式取决于这个变量。我可以进入每个命令的代码后台并添加逻辑,但那似乎相当笨拙,我认为肯定有更好的方法。我看到了使用“CanExecute”的解决方案,但那是针对ICommand类型的命令,而我正在使用RelayCommand类型的命令。


你好,你是否在使用 mvvm-light - SWilko
@dellywheel 是的,抱歉我应该提到那个。 - Snicklefritz
好的框架 :) 我马上会发布一个例子 - SWilko
2个回答

3
你可以使用 mvvm-lightRelayCommand CanExecute 在 KeyBinding Commands 中。 这里是一个简单的例子,我根据 SomeProperty 阻止了使用P键。

MainViewModel.cs

private bool someProperty = false;

    public bool SomeProperty
    {
        get { return someProperty = false; }
        set { Set(() => SomeProperty, ref someProperty, value); }
    }

    private RelayCommand someCommand;
    public RelayCommand SomeCommand
    {
        get
        {
            return someCommand ??
                new RelayCommand(() =>
            {
                //SomeCommand actions
            }, () =>
            {
                //CanExecute
                if (SomeProperty)
                    return true;
                else
                    return false;
            });
        }
    }

在前端的MainWindow.xaml中,还有一个名为Binding的内容。

<Window x:Class="WpfApplication12.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
<Window.InputBindings>
    <KeyBinding Key="P" Command="{Binding SomeCommand}" />
</Window.InputBindings>
<Grid>
    <TextBox Width="200" Height="35" />
</Grid>

希望能帮到你。

2

在您的视图模型中使用命令的CanExecute方法。

然后您可以在XAML中删除IsEnabled属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接