[英]TreeViewItems and Keybinding
我正在嘗試使用此處介紹的技術(第一個答案)在TreeView項目上設置鍵綁定。 因此,我在XAML中有一個TreeView,在TreeView項的ViewModel中定義了ICommand屬性,並注冊了一個輔助類來幫助附加屬性以支持TreeViewItem樣式的鍵綁定。 但是每次實際上只在我的TreeView的第一項上調用命令時,無論實際上選擇了哪一項。 為什么會這樣,我該如何解決? 還是有一些更好的方法可以在不破壞MVVM模式的情況下在TreeViewItems上設置鍵綁定?
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>
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();
}
}
這是遲到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放置在該樣式之上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.