【问题标题】:WPF change bound command for keybindings based on property?WPF基于属性更改键绑定的绑定命令?
【发布时间】:2017-01-20 05:43:07
【问题描述】:

我有一个 xaml 窗口,我想根据布尔属性的值将 Escape key 绑定到我的视图模型中的不同命令。

IsSearching == true,绑定到 CancelSearch 命令

IsSearching == false,绑定到关闭命令。

有没有办法在没有代码的情况下做到这一点?

【问题讨论】:

    标签: .net wpf xaml mvvm


    【解决方案1】:
    <Window>
     <Window.InputBindings>
         <KeyBinding Command="{Binding SomeCommand}" Key="F5"/>
     </Window.InputBindings>
    </Window>
    

    这是一种解决方法

    private ICommand someCommand;
    public ICommand SomeCommand
    {
        get
        {
            return someCommand 
                ?? (someCommand = new ActionCommand(() =>
                {
    
                    if(IsSearching)
                       OnCancelExecute();
                    else
                       OnCloseExecute();
                }));
        }
    }
    

    【讨论】:

    • 这是唯一合理的方法。 VM 必须知道它当前正在做什么,并且当发出取消命令时,它必须取消此操作。
    • 我说不是100%,可能有人有干净的方式
    【解决方案2】:

    您不能直接在 XAML 中执行所有操作,有时还需要一些代码隐藏。
    如果我不想花费数小时搜索纯 XAML 解决方案,我会这样做。

    在您的 XAML 中,为您的键绑定提供 x:Name(此处为 searchKey)。
    然后在代码隐藏中,在构造函数中添加类似这样的内容:

    public partial class YourView
    {
        public YourView()
        {
            InitializeComponent();
            var vm = DataContext as YourViewModel;
            vm.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName != "IsSearching")
                        return;
    
                    searchKey.Command = vm.IsSearching ? vm.SearchCommand : vm.CancelCommand:
                };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多