![]() |
年轻有为的茴香 · 15 Population ...· 2 月前 · |
![]() |
含蓄的红薯 · ctp-follow/text.txt ...· 3 月前 · |
![]() |
飞翔的橡皮擦 · 【GNZ48陈佳莹】《不曾后悔》直拍focu ...· 3 月前 · |
![]() |
聪明的领带 · Android中mediaplayer的se ...· 7 月前 · |
wpf treeview |
https://cloud.tencent.cn/developer/information/%E5%A6%82%E4%BD%95%E5%8F%96%E6%B6%88%E7%94%A8%E6%88%B7%E7%9A%84WPF%20TreeView%E7%82%B9%E5%87%BB%EF%BC%9F |
![]() |
坏坏的香槟
5 月前 |
在WPF中,取消用户的TreeView点击事件可以通过以下几种方法实现:
在TreeView的ItemContainerStyle中,可以使用命令绑定来绑定一个自定义的命令。这个命令可以在ViewModel中定义,并在命令中处理点击事件。
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="Command" Value="{Binding DataContext.MyCommand, RelativeSource={RelativeSource AncestorType=TreeView}}" />
<Setter Property="CommandParameter" Value="{Binding}" />
</Style>
</TreeView.ItemContainerStyle>
然后在ViewModel中定义MyCommand命令,并在Execute方法中处理点击事件。
public ICommand MyCommand { get; set; }
public MyViewModel()
MyCommand = new RelayCommand<object>(ExecuteMyCommand);
private void ExecuteMyCommand(object parameter)
// 处理点击事件
}
可以使用附加属性来处理点击事件。在附加属性中,可以使用事件触发器来处理点击事件。
public class TreeViewItemBehavior
public static ICommand GetCommand(DependencyObject obj)
return (ICommand)obj.GetValue(CommandProperty);
public static void SetCommand(DependencyObject obj, ICommand value)
obj.SetValue(CommandProperty, value);
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(TreeViewItemBehavior), new UIPropertyMetadata(null, OnCommandChanged));
private static void OnCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
var item = sender as TreeViewItem;
if (item == null)
return;
if (e.NewValue != null)
item.PreviewMouseLeftButtonDown += OnItemPreviewMouseLeftButtonDown;
item.PreviewMouseLeftButtonDown -= OnItemPreviewMouseLeftButtonDown;
private static void OnItemPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
var item = sender as TreeViewItem;
if (item == null)
return;
var command = GetCommand(item);
if (command != null)
if (command.CanExecute(item.DataContext))
command.Execute(item.DataContext);
}
然后在XAML中使用附加属性:
<TreeView>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="local:TreeViewItemBehavior.Command" Value="{Binding DataContext.MyCommand, RelativeSource={RelativeSource AncestorType=TreeView}}" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
这样,就可以在ViewModel中处理点击事件了。