我正在尝试使用here描述的技术在我的TreeView项上设置键绑定(第一个答案)。因此,我有一个XAML格式的TreeView,一个在TreeView项的ViewModel中定义的ICommand属性,以及一个注册附加属性以支持TreeViewItem样式的键绑定的帮助器类。但每次该命令只在我的TreeView的第一个项目上调用,而不管实际选择的是哪个项目。为什么会这样?我该如何修复它?或者有没有更好的方法在TreeViewItems上设置键绑定而不破坏MVVM模式?
XAML
<TreeView x:Name="tr" ItemsSource="{Binding Root}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="local:AttachedTVIBinding.InputBindings">
<Setter.Value>
<InputBindingCollection>
<KeyBinding Key="A" Command="{Binding SomeCommand}"/>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding SomeCommand}"/>
</InputBindingCollection>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>树视图项的ViewModel
public class ConfigurationNodeViewModel : INotifyPropertyChanged
{
private DelegateCommand _someCommand;
public DelegateCommand SomeCommand
{
get { return _editDesignCommand; }
}
}Helper类(与提供的链接完全相同)
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();
}
}发布于 2014-10-23 23:43:20
这是一个延迟了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中使用。您也可以使用为TreeViewItem定义样式的相同ResourceDictionary,但需要将InputBindingCollection放在此样式之上。
https://stackoverflow.com/questions/7464360
复制相似问题