WPF,树视图选择更改

编程入门 行业动态 更新时间:2024-10-08 00:28:49
本文介绍了WPF,树视图选择更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有办法捕捉到试图在WPF的TreeView控件来改变当前所选的项目,并可能取消呢?

Is there a way to capture an attempt to change currently selected item in the WPF's TreeView and possibly cancel it?

在TreeView元素代表了一些属性页面。我想,如果他想放弃页面上所做的更改,保存它们还是停留在当前页面,询问用户。

Elements in the treeview represent pages with some properties. I would like to ask user if he wants to abandon changes made on the page, save them or stay in the current page.

推荐答案

那么你可能不会喜欢的答案...的WPF TreeView控件是一个不友好的家伙。好吧,首要的事情...

Well you're probably not going to like the answer... the WPF TreeView is an unfriendly fellow. Ok, first things first...

的捕捉试图改变所选的项目的:

要做到这一点,最简单的方法是处理 SelectedItemChanged 事件:

The easiest way to do this is to handle the SelectedItemChanged event:

private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { e.Handled = true; }

不幸的是,如果你使用MVVM,那么你就需要处理这样的一个里面的附加属性。获得一个比较复杂一点,现在,如果你要创建一个附加属性来处理 SelectedItemChanged 事件,然后是你还不如实施的SelectedItem 附加属性,你可以在绑定到双向模式。我不会记录如何,因为有很多这种在线教程做到这一点在这里。

Unfortunately, if you're using MVVM, then you'll need to handle this inside an Attached Property. Getting a bit more complicated now, if you're going to create an Attached Property to handle the SelectedItemChanged event, then you might as well implement a SelectedItem Attached Property that you could bind to in Two-Way Mode. I won't document how to do this here because there are plenty of online tutorials for this.

的 ...并可能取消的:

如果你有一个的SelectedItem 附加属性,那么你就可以监控时属性更改。当然还有一个catch ...的变化进入您的视图模型的时候,UI已经改变。因此,尽管你可以阻止发生在视图模型中的数据的变化,你不能停止在UI所做出的选择。

If you have a SelectedItem Attached Property, then you can monitor when that property changes. There is a catch of course... by the time the change comes into your view model, the UI has already changed. So, although you can stop the change from happening to the data in the view model, you cannot stop the selection being made in the UI.

这是不是一个可怕的问题但是,因为有双向绑定,您将能够在必要时设置的用户界面选择回到上一个项目......看看这个伪代码:

This is not a terrible problem though, because with a Two-Way Binding, you will be able to set the UI selection back to the previous item if necessary... take a look at this pseudo code:

public YourDataType SelectedItem { get { return selectedItem; } set { if (selectedItem != value) { if (selectedItem.HasChanges) { if (WindowManager.UserAcceptsLoss()) { selectedItem = value; NotifyPropertyChanged("SelectedItem"); } else ResetSelectedItem(selectedItem); } else { selectedItem = value; NotifyPropertyChanged("SelectedItem"); } } } }

要满足您的要求,您有很多工作要做...祝你好运。

To fulfil your requirements, you have a lot of work ahead... good luck with that.

更多推荐

WPF,树视图选择更改

本文发布于:2023-11-12 20:47:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582493.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   WPF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!