WPF - 绑定关键状态的可见性

问题描述 投票:2回答:1

我需要将WPF UserControl上的控件的可见性绑定到Alt键的状态,如果可能的话通过转换器。只有在按下ALT键时才能看到Button,解决方案不应该集成在Code Behind文件中,因为我使用的是PRISM / Unity的严格MVVM模式。

一个完美的解决方案包括编写一个能够将键盘键状态转换为用户控件的Visiblity属性的新转换器,但我对转换器的经验很少,而且我自己无法提供解决方案。

c# .net wpf mvvm ivalueconverter
1个回答
7
投票

这是一个完整的例子

XAML

<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事件传递key参数

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;
});

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.