I have a data source:
private List<PlayData> _treeData = new List<PlayData>();
private void Test()
{
_treeData.Add(new PlayData()
{
BoolList = new List<bool>() { true, false, true },
Name = "A"
});
_treeData.Add(new PlayData()
{
BoolList = new List<bool>() { true, false, true },
Name = "B"
});
DataContext = this;
}
How do I bind this 开发者_StackOverflow中文版in XAML so that Name is the parent and the list of Bool's are the children. I tryed unsuccesfully with this:
<TreeView x:Name="treeView" Height="200" ItemsSource="{Binding Path=TreeData}" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=BoolList, Mode=TwoWay}" >
<TextBlock FontWeight="Bold" Text="{Binding Path=Name, Mode=TwoWay}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
It's not clear from your sample what you're doing - but in essence
- You have to have a public property defined in code called
TreeData
(missing from your sample, but assuming this is the one that returns _treeData
) BoolList
needs to be a child property ofTreeData
(that seems to be the case)- You need to define a HierarchicalTemplate for each element in your treeview that contains child elements.
- Define a regular
DataTemplate
for each element in your treeview that does not contain child elements
If there are different data types as in your case you need to declare the type of the object as in
<HierarchicalDataTemplate DataType="{x:Type foo:PlayData}"
ItemsSource="{Binding BoolList}">
Order of templates is important if there can be multiple matches.
The _treeData field needs to be exposed as a property in order to be bound. It's not clear from your sample code if you're doing that or not.
You can also get rid of Mode=TwoWay on both of your Bindings because there is no input to push back to the source values.
精彩评论