如果通过转换器以某种方式可能,我需要将WPF UserControl上的控件的可见性绑定到Alt键的状态。只有在按下ALT键时才能看到Button,解决方案不应该集成在Code Behind文件中,因为我使用的是PRISM / Unity的严格MVVM模式。
一个完美的解决方案包括编写一个能够将键盘键的状态转换为用户控件的Visiblity属性的新转换器,但我对转换器的经验很少,而且无法想出一个解决方案。
答案 0 :(得分:7)
这是一个完整的例子
<Window x:Class="Playground.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Playground"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Title="MainWindow" Height="350" Width="525">
<Window.InputBindings>
<KeyBinding Modifiers="Alt" Key="LeftAlt" Command="{Binding AltPressedCommand}" />
</Window.InputBindings>
<Window.Resources>
<BooleanToVisibilityConverter x:Key="boolToVisibilityConverter"/>
</Window.Resources>
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyUp">
<i:InvokeCommandAction Command="{Binding AltUnpressedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
<Button Content="My Button" Visibility="{Binding IsAltPressed, Converter={StaticResource boolToVisibilityConverter}}"/>
</Grid>
</Window>
public class MainWindowViewModel : NotificationObject
{
public MainWindowViewModel()
{
AltPressedCommand = new DelegateCommand(() => IsAltPressed = true);
AltUnpressedCommand = new DelegateCommand(() => IsAltPressed = false);
}
public DelegateCommand AltPressedCommand { get; set; }
public DelegateCommand AltUnpressedCommand { get; set; }
private bool _IsAltPressed;
public bool IsAltPressed
{
get { return _IsAltPressed; }
set
{
if (value != _IsAltPressed)
{
_IsAltPressed = value;
RaisePropertyChanged("IsAltPressed");
}
}
}
}
控件的可见性通过BooleanToVisibilityConverter
绑定到布尔属性。
然后我使用两个命令。使用KeyBinding按下Alt键时触发,而当键发生时触发第二个键。当你应该添加密钥时,我没有检查 Alt 键。如果你想纯粹使用MVVM,这可能会变得棘手,因为你需要向命令发送一个参数来说明正在按下的键。
我使用以下行为从PreviewKeyUp
事件
public class PreviewKeyUpBehavior : Behavior<UIElement>
{
#region Properties
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(PeviewKeyUpBehavior));
#endregion
#region Methods
protected override void OnAttached()
{
AssociatedObject.PreviewKeyUp += OnPreviewKeyUp;
base.OnAttached();
}
private void OnPreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (Command == null) return;
// Execute command and send the key as the command parameter
Command.Execute(e.Key == Key.System ? e.SystemKey : e.Key);
}
#endregion
}
这将在PreviewKeyUp
被触发时引发绑定命令,并将该键作为命令参数发送。然后,我按如下方式更改了View和ViewModel中的代码:
<!-- Used behaviors instead of triggers -->
<i:Interaction.Behaviors>
<local:PreviewKeyUpBehavior Command="{Binding KeyUnpressedCommand}"/>
</i:Interaction.Behaviors>
更改命令以获取可为空的关键参数
public DelegateCommand<Key?> KeyUnpressedCommand { get; set; }
并实施了它
KeyUnpressedCommand = new DelegateCommand<Key?>(key =>
{
if (key == Key.LeftAlt)
IsAltPressed = false;
});
希望这有帮助