wpf TreeView - 如何在 IsExpanded 属性更改时调用函数 [英] wpf TreeView - How to call function on IsExpanded property change
问题描述
当 TreeViewItem 属性 IsExpanded 更改时,XAML 中是否可以调用函数?
Is there a way in XAML to call a function when the TreeViewItem property IsExpanded changes?
我相信不太好的替代方法是循环遍历所有 TreeViewItems 并执行 item.IsExpanded += 处理程序调用,如果我理解正确的话.
I believe the not so good alternative would be to loop through all TreeViewItems and do an item.IsExpanded += handler call if I understand things correctly.
或者我想我可以检查扩展器元素上的点击次数.
Or I could check for clicks on the expander element I guess.
我正在做的是保持树的展开/折叠状态.请在建议替代方法来坚持这一点之前回答第一个问题,只是为了让我了解属性和 xaml.
What I'm doing is persisting the expand/collapse state of the tree. Please answer the first question before suggesting alternative ways to persist this just to edify me on properties and xaml.
推荐答案
我会使用以下方法将 TreeViewItem 的 IsExpanded 属性绑定到我的模型:
I would bind the IsExpanded property of the TreeViewItem to my model using something like:
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
<Setter Property="IsExpanded" Value="{Binding IsExpanded}" />
</Style>
</TreeView.ItemContainerStyle>
然后我可以运行模型并获取 IsExpanded 的值并保存它.此外,在恢复时,只需设置 IsExpanded 属性即可.
Then I can run thru the model and get the value for IsExpanded and save it. Additionally, when restoring, simply set the IsExpanded property.
由于更改时需要调用其他代码,请像这样实现 IsExpanded:
Since you need to call other code when changed, implement IsExpanded like so:
private bool _IsExpanded;
public bool IsExpanded
{
get { return _IsExpanded; }
set
{
if (_IsExpanded == value) return;
_IsExpanded = value;
NotifyPropertyChanged( "IsExpanded" );//or however you need to do it
CallSomeOtherFunc();//this is the code that you need to be called when changed.
}
}
这篇关于wpf TreeView - 如何在 IsExpanded 属性更改时调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!