gpt4 book ai didi

c# - 如何在运行时从用户分配键盘快捷键,WPF MVVM

转载 作者:行者123 更新时间:2023-12-03 10:32:15 24 4
gpt4 key购买 nike

正如标题所说,我正在寻找一种在运行时使用 WPF MVVM 模式从用户分配键盘快捷键的方法。我知道我可以像这样在开始时定义键盘快捷键:

<Window.InputBindings>
<KeyBinding Command="{Binding MyCommand}" Key="A"/>
</Window.InputBindings>

我还看到有一种方法可以 parse input bindings from a user .然而,我正在努力将一个输入绑定(bind)从我的 ViewModel 绑定(bind)到 MainWindow 的 InputBinding。我不知道如何实现这一点。这是我的 MainWindow 中的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
}

这是我的 ViewModel 中的一些示例代码:
public partial class MainWindowViewModel : Window, INotifyPropertyChanged
{
public MainWindowViewModel()
{
KeyBinding kb = new KeyBinding { Key = Key.T, Command = MyCommand };
this.InputBindings.Add(kb);
}
}

我知道 this.InputBindings.Add(kb);部分可能应该用其他东西代替;而是将键绑定(bind)添加到 MainWindow 的 InputBinding。但是,我不知道如何使用 MVVM 模式来做到这一点。因此:我将如何去做呢?

最佳答案

您可能会在 View 模型中定义输入绑定(bind),但您仍然需要以某种方式将它们添加到 View 中。

例如,您可以使用为您执行此操作的附加行为:

public class InputBindingsBehavior
{
public static readonly DependencyProperty InputBindingsProperty = DependencyProperty.RegisterAttached(
"InputBindings", typeof(IEnumerable<InputBinding>), typeof(InputBindingsBehavior), new PropertyMetadata(null, new PropertyChangedCallback(Callback)));

public static void SetInputBindings(UIElement element, IEnumerable<InputBinding> value)
{
element.SetValue(InputBindingsProperty, value);
}
public static IEnumerable<InputBinding> GetInputBindings(UIElement element)
{
return (IEnumerable<InputBinding>)element.GetValue(InputBindingsProperty);
}

private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UIElement uiElement = (UIElement)d;
uiElement.InputBindings.Clear();
IEnumerable<InputBinding> inputBindings = e.NewValue as IEnumerable<InputBinding>;
if (inputBindings != null)
{
foreach (InputBinding inputBinding in inputBindings)
uiElement.InputBindings.Add(inputBinding);
}
}
}

查看型号:
public partial class MainWindowViewModel
{
public MainWindowViewModel()
{
KeyBinding kb = new KeyBinding { Key = Key.T, Command = MyCommand };
InputBindings.Add(kb);
}

public List<InputBinding> InputBindings { get; } = new List<InputBinding>();

public ICommand MyCommand => ...
}

查看:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Window18" Height="300" Width="300"
local:InputBindingsBehavior.InputBindings="{Binding InputBindings}">
<Grid>

</Grid>
</Window>

关于c# - 如何在运行时从用户分配键盘快捷键,WPF MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53816710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com