开发者

WPF: Binding TreeView

开发者 https://www.devze.com 2023-01-30 01:18 出处:网络
I have a data source: private List<PlayData> _treeData = new List<PlayData>(); private void Test()

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

  1. 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)
  2. BoolList needs to be a child property of TreeData (that seems to be the case)
  3. You need to define a HierarchicalTemplate for each element in your treeview that contains child elements.
  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消