c# - WPF - 将可见性绑定(bind)到键的状态

标签 c# .net wpf mvvm ivalueconverter

我需要将 WPF UserControl 上控件的可见性绑定(bind)到 Alt 键的状态,如果可以通过转换器的话。按钮应该只有在按下 ALT 键时才可见,解决方案不应集成到代码隐藏文件中,因为我使用 PRISM/Unity 在严格的 MVVM 模式下工作。

一个完美的解决方案包括编写一个新的转换器,该转换器能够将键盘键的状态转换为用户控件的可见性属性,但我在转换器方面经验不足,无法想出一个自己解决。

最佳答案

这是一个完整的例子

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>

View 模型

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 绑定(bind)到 bool 属性。 然后我使用两个命令。当使用 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 时引发绑定(bind)命令,并将 key 作为命令参数发送。然后我更改了 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;
});

希望对你有帮助

关于c# - WPF - 将可见性绑定(bind)到键的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19764661/

相关文章:

c# - 委托(delegate)、 Action 、事件、Lambda 表达式和 MVVM

wpf - WPf 中 Intellisense 支持的 TextBox

c# - Windows Phone 中 richtextbox 的使用

c# - 使用 Fluent Validation 进行条件验证

c# - 是否有用于 Xml 的 Json2Csharp.com?

c# - 为什么我的上下文菜单不能使用 DataContext={Binding}?

c# - 打包(.zip)一个字节数组文件.net core

c# - 类似于 Extension Methods Functionality - 我们可以扩展属性吗

c# - WPF 网格拆分器 : How to move programmatically?

c# - System.Web 可以与具有完整框架的 ASP.Net Core 一起使用吗