C# WPF有条件地启用键绑定

C# WPF有条件地启用键绑定,c#,wpf,linq,entity-framework,xaml,C#,Wpf,Linq,Entity Framework,Xaml,我有一个WPF项目,在该项目中,我试图根据viewmodel中的公共属性状态启用/禁用键盘快捷键。也许有一个超级简单的解决方案,但我是WPF的新手,从谷歌找不到任何东西。以下是我的工作XAML: <KeyBinding Modifiers="Control" Key="p" Command="{Binding PrintCommand}" CommandParameter="{Binding OpenEvent}"/> 以下是我想做的: <KeyBinding Modi

我有一个WPF项目,在该项目中,我试图根据viewmodel中的公共属性状态启用/禁用键盘快捷键。也许有一个超级简单的解决方案,但我是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种不同的快捷方式,这取决于这个变量。我可以为20个命令中的每一个都编写代码并添加逻辑,但这似乎相当困难,我认为必须有更好的方法。我见过使用“CanExecute”的解决方案,但这是针对ICommand类型的命令的,我正在使用RelayCommand类型的命令。

在视图模型上使用命令的CanExecute方法


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

您可以在KeyBinding命令中使用
mvvm指示灯
RelayCommand
来执行。下面是一个简单的例子,我基于
SomeProperty

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

<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>


希望能有所帮助

您好,您使用的是
mvvmlight
?@dellywheel是的,很抱歉我应该提到这一点。良好的框架:)我稍后会发布一个示例