C# 树元素和键绑定
我正在尝试使用所描述的技术(第一个答案)在我的TreeView项上设置keybinding。因此,我在XAML中有一个TreeView,一个在TreeView项的ViewModel中定义的ICommand属性,以及一个注册附加属性以支持TreeView项样式的键绑定的帮助器类。但是每次只在我的树视图的第一个项目上调用该命令时,不管实际选择了哪个项目。这是为什么?我该如何修复它?或者有没有更好的方法可以在不破坏MVVM模式的情况下在TreeViewItems上设置keybinding XAML 助手类(与提供的链接完全相同)C# 树元素和键绑定,c#,wpf,mvvm,key-bindings,C#,Wpf,Mvvm,Key Bindings,我正在尝试使用所描述的技术(第一个答案)在我的TreeView项上设置keybinding。因此,我在XAML中有一个TreeView,一个在TreeView项的ViewModel中定义的ICommand属性,以及一个注册附加属性以支持TreeView项样式的键绑定的帮助器类。但是每次只在我的树视图的第一个项目上调用该命令时,不管实际选择了哪个项目。这是为什么?我该如何修复它?或者有没有更好的方法可以在不破坏MVVM模式的情况下在TreeViewItems上设置keybinding XAML 助
这里有一个3年后的答案,但可能对某些人有用 解决方案是使用一种样式,通过设置x:shared=“False”,应用包含KeyBinding和MouseBinding元素的非共享资源。这允许创建多个InputBindingCollection实例,因为默认情况下WPF只创建样式的单个实例
<InputBindingCollection x:Key="myBindings" x:Shared="False">
<KeyBinding Key="A" Command="{Binding SomeCommand}"/>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding SomeCommand}"/>
</InputBindingCollection>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="local:AttachedTVIBinding.InputBindings" Value="{DynamicResource myBindings}"/>
</Style>
请注意,x:Shared只能在已编译的ResourceDictionary中使用。
您也可以使用同一个ResourceDictionary,您在其中为TreeViewItem定义了一个样式,但InputBindingCollection需要放在该样式之上。您能为我们提供更多信息或您的代码吗?您的密钥绑定实际上在做什么?它如何满足所选treeview项目的需要?你在哪里做附加属性绑定?我已经在最初的帖子中包含了一些代码。我想要完成的是,每当用户按下某个键时,在当前所选TreeViewItem的ViewModel中执行命令。但是也许我把我的任务复杂化了,还有一个更简单的方法。嗨,我也有同样的问题,你找到解决办法了吗?
public class ConfigurationNodeViewModel : INotifyPropertyChanged
{
private DelegateCommand _someCommand;
public DelegateCommand SomeCommand
{
get { return _editDesignCommand; }
}
}
public class AttachedTVIBinding : Freezable
{
public static readonly DependencyProperty InputBindingsProperty =
DependencyProperty.RegisterAttached("InputBindings", typeof(InputBindingCollection), typeof(AttachedTVIBinding),
new FrameworkPropertyMetadata(new InputBindingCollection(),
(sender, e) =>
{
var element = sender as UIElement;
if (element == null) return;
element.InputBindings.Clear();
element.InputBindings.AddRange((InputBindingCollection)e.NewValue);
}));
public static InputBindingCollection GetInputBindings(UIElement element)
{
return (InputBindingCollection)element.GetValue(InputBindingsProperty);
}
public static void SetInputBindings(UIElement element, InputBindingCollection inputBindings)
{
element.SetValue(InputBindingsProperty, inputBindings);
}
protected override Freezable CreateInstanceCore()
{
return new AttachedTVIBinding();
}
}
<InputBindingCollection x:Key="myBindings" x:Shared="False">
<KeyBinding Key="A" Command="{Binding SomeCommand}"/>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding SomeCommand}"/>
</InputBindingCollection>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="local:AttachedTVIBinding.InputBindings" Value="{DynamicResource myBindings}"/>
</Style>