有没有办法捕获更改 WPF TreeView 中当前选定项目的尝试并可能取消它?
树视图中的元素代表具有某些属性的页面。我想询问用户是否要放弃在页面上所做的更改、保存它们或保留在当前页面。
一个更简单的解决方案。覆盖 PreviewMouseDown,您将获得所需的结果。
private void Tree_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
// first did the user click on a tree node?
var source = e.OriginalSource as DependencyObject;
while (source != null && !(source is TreeViewItem))
source = VisualTreeHelper.GetParent(source);
source = source as TreeViewItem;
if (source == null) return;
var treeView = sender as TreeView;
if (treeView == null) return;
// validate our current item to decide if we allow the change
// or do whatever checks you wish
if (!ItemIsValid(treeView.SelectedItem))
{
// it's not valid, so cancel the attempt to select an item.
e.Handled = true;
}
// Maybe you want to check the about to be selected value?
MyClass data = source.DataContext;
if (!CanSelect(data))
{
// we can't select this, so cancel the attempt to select.
e.Handled = true;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)