我目前正在尝试将我的业务对象绑定到树视图作为根。而它的收藏属性就像孩子一样。 [我想通过BINDING实现这一目标]
像这样。
public object MyBusinessObject
{
private int _number;
private bool _isSelected;
private ObservableCollection<AnotherObject> _other = new ObservableCollection<AnotherObject>();
public int Number { get {return _number;} set {_number = value;}}
public bool IsSelected{ get {return _isSelected;} set {_isSelected= value;}}
public ObservableCollection<AnotherObject> Children { get {return _other;}}
}
我希望我的树视图能够像这样表示:
我不知道如何在xaml中执行此操作:
<TreeView x:Name="_tv" ItemsSource="{Binding Path=MyBusinessObject}" >
<TreeView.Resources>
<HierarchicalDataTemplate>
<CheckBox Content="{Binding Path=Number} IsChecked="{Binding Path=IsSelected}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
我知道以上是不对的,但我想知道是否有办法正确地做到这一点。
谢谢和问候,
答案 0 :(得分:6)
当然,您可以使用HierarchicalDataTemplate.ItemTemplate属性来定义要用于AnotherObject实例集合的数据模板。
<TreeView ItemsSource="{Binding SomeCollectionOfObjects}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<!-- This is used for your AnotherObject instances -->
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
<!-- This is used for your MyBusinessObject instances -->
<CheckBox Content="{Binding Number}" IsChecked="{Binding IsSelected}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>