开发者

How to achieve hierarchical data binding?

Learning WPF here and I'm trying to get my head around hierarchical data binding.

This is my situation:

public class A
{
    public int Id { ... }
    public IEnumerable<B> Children { ... }
}

public class B
{
    public string SomeValue { ... }
}

I want to use a ItemsControl to display a collection of A and for each occurance of A I want an inner ItemsControl to display A.Children.

I thought this would do the trick but, apparently, I have much to learn yet...

<ItemsControl x:Name="icCollectionOfAs" ItemsSource="{Binding}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid Width="auto" Height="auto">
                <TextBlock Text="{Binding Id}" />
                <ItemsControl ItemsSource="{Binding Children}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding SomeValue}" />
                        </DataTemplate>
                    </ItemsControl.ItemTemplate&开发者_开发技巧gt;
                </ItemsControl>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Then, in code-behind...

icCollectionOfAs.ItemsSource = createSomeAsWithChildBsInThem();

The result of all this is nothing gets shown. Why?

Thanks


You should not specify the ItemsSource both in XAML (ItemsSource="{Binding}") and code behind (icCollectionOfAs.ItemsSource = createSomeAsWithChildBsInThem();) the XAML might have been called later.

The rest seems fine to me except that the TextBlock for the ID will probably be hidden behind the ItemsControl for the children as you use a Grid without rows or columns rather than a StackPanel.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜