[英]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.