views:

595

answers:

3

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?

A: 

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

Corey Sunwold
I tried creating an override for ToString(), removed the ItemTemplate from the xaml code, but the ToString method isn't being called.
eriksmith200
A: 

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>
eriksmith200
In combination with the an ObservableDictionary this works pretty well for me.an implementation of an ObservableDictionary is described here:http://drwpf.com/blog/Home/tabid/36/EntryID/8/Default.aspxadaptation for Silverlight:http://blog.treehouseconsulting.co.uk/post/2009/06/17/ObservableDictionary-in-Silverlight.aspx
eriksmith200
A: 

The same bug(?) exists in ListBox, a solution is provided here: http://stackoverflow.com/questions/1680213/use-uielements-as-itemssource-of-listbox-in-silverlight

That particular fix does not work for TreeView

eriksmith200