Wpf树视图数据库隐藏/显示展开/折叠图标
-
28-09-2019 - |
题
我实现了一个WPF按需加载树视图,如下所述 这 (很好)的文章。在上述解决方案中,使用虚拟元素来保存展开 +
图标/树视图项行为。当用户点击扩展器时,虚拟项被替换为真实数据。
我想通过添加属性来细化模型 public bool HasChildren { get { ... } }
在我的支持下 TreeNodeViewModel
.
问题:
如何绑定此属性以隐藏/显示展开图标(在XAML中)?我无法找到合适的触发器/setter组合。
(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);
}
}
}
这是您的自定义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>
正如您所看到的,第一个项目是常规项目,第二个是您的自定义项目。请注意,它有一个孩子。接下来,您可以绑定 HasChildren 属性到你的ViewModel中的一些布尔对象,或者只是简单地通过设置HasChildren来测试我的自定义类 错误 来自上述XAML背后的代码:
xyz.HasChildren = false;
现在,尽管你的元素有一个孩子,展开按钮不显示,所以这意味着,我的自定义类工作。
我希望我帮助了你,但如果你有任何问题,请随时询问。
皮奥特
其他提示
在快速查看Josh的代码后,我发现了这个构造函数:
protected TreeViewItemViewModel(TreeViewItemViewModel parent, bool lazyLoadChildren)
{
_parent = parent;
_children = new ObservableCollection<TreeViewItemViewModel>();
if (lazyLoadChildren)
_children.Add(DummyChild);
}
所以,如果你通过 false
为 lazyLoadChildren
参数从继承ViewModel类,+图标不应该出现,因为没有添加DummyChild。由于您似乎知道您的物品是否有孩子,因此您应该能够为 lazyLoadChildren
财产。还是我错过了什么?