[英]WPF Conditionally Enable KeyBinding
我有一个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-light
RelayCommand
CanExecute。 下面是一个简单的例子,我根据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>
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.