Jul*_*ner 5 data-binding wpf treeview expand collapse
我实现了一个 WPF 按需加载树视图,就像这篇(非常好的)文章中描述的那样。在提到的解决方案中,使用一个虚拟元素来保留展开+
图标/树状视图项的行为。当用户单击扩展器时,虚拟项目将替换为真实数据。
我想通过向public bool HasChildren { get { ... } }
我的 backing添加一个属性来优化模型TreeNodeViewModel
。
问题:
如何绑定此属性以隐藏/显示展开图标(在 XAML 中)?我找不到合适的触发器/设置器组合。
(INotifyPropertyChanged 已正确实施。)
谢谢你的时间。
更新 1:
我想使用我的属性public bool HasChildren
而不是使用虚拟元素。
确定一个物品是否有孩子的成本有点高,但仍然比去取孩子便宜得多。
朱利安,
这是一个非常好的问题。为什么不尝试编写自己的树视图项呢?:) 我的意思是,不是从头开始,只是从现有的 TreeViewItem 派生并添加您的属性。我已经准备了一个快速示例,但您可以随意修改它(如果有些内容不完全清楚,请提出问题)。开始了:
public class TreeViewItem_CustomControl : TreeViewItem
{
static TreeViewItem_CustomControl()
{
HasChildrenProperty = DependencyProperty.Register("HasChildren", typeof(Boolean), typeof(TreeViewItem_CustomControl));
}
static DependencyProperty HasChildrenProperty;
public Boolean HasChildren
{
get
{
return (Boolean)base.GetValue(HasChildrenProperty);
}
set
{
if (value)
{
if (this.Items != null)
{
this.Items.Add(String.Empty); //Dummy item
}
}
else
{
if (this.Items != null)
{
this.Items.Clear();
}
}
base.SetValue(HasChildrenProperty, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是您的自定义 TreeViewItem 的代码。现在让我们在 XAML 中使用它:
<TreeView>
<TreeViewItem Header="qwer">
Regulat tree view item.
</TreeViewItem>
<CustomTree:TreeViewItem_CustomControl x:Name="xyz" Header="temp header" Height="50">
<TreeViewItem>Custom tree view item, which will be removed.</TreeViewItem>
</CustomTree:TreeViewItem_CustomControl>
</TreeView>
Run Code Online (Sandbox Code Playgroud)
如您所见,第一个项目是常规项目,第二个项目是您的自定义项目。请注意,它有一个孩子。接下来,您可以将HasChildren属性绑定到 ViewModel 中的某个布尔对象,或者只是通过从上述 XAML 背后的代码将 HasChildren 设置为False来测试我的自定义类:
xyz.HasChildren = false;
Run Code Online (Sandbox Code Playgroud)
现在,尽管您的元素有一个子元素,但未显示展开按钮,因此这意味着我的自定义类可以工作。
我希望我对您有所帮助,但如果您有任何疑问,请随时询问。
彼得。