开发者

Silverlight 3: Using list of UserControls as ItemsSource for TreeView

开发者 https://www.devze.com 2022-12-12 15:34 出处:网络
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 crash开发者_运维技巧es as soon as I add som

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 crash开发者_运维技巧es 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?


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>


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.

0

精彩评论

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