Question

I want to populate a TreeView with UserControls, but I only want the Name property to show up, not the entire UserControl. The following code gives me weird crashes as soon as I add something to myUCs:

C#:

var myUCs = new ObservableCollection<UserControl>();
MyTreeView.ItemsSource = myUCs;

XAML:

<controls:TreeView x:Name="MyTreeView">
    <controls:TreeView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </controls:TreeView.ItemTemplate>
</controls:TreeView> 

Does anyone know how to use a list of UserControls as an ItemSource for TreeViews?

Was it helpful?

Solution

I found one not so convenient workaround: instead of a List of UserControls, use a Dictionary, and change the XAML to:

<controls:TreeView x:Name="MyTreeView">
    <controls:TreeView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Key.Name}"/>
        </DataTemplate>
    </controls:TreeView.ItemTemplate>
</controls:TreeView>

OTHER TIPS

The same bug(?) exists in ListBox, a solution is provided here: Use UIElements as ItemsSource of ListBox in Silverlight

That particular fix does not work for TreeView

You may have to create your own class that extends UserControl and override the ToString() method so that it returns the name property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top