Skip to main content
Home Forums Silverlight Design Designing with Silverlight Default HierarchicalDataTemplate for TreeView
2 replies. Latest Post by grimus on April 6, 2009.
(0)
grimus
Member
5 points
16 Posts
03-31-2009 11:32 AM |
I'm creating a control that inherits from the Silverlight Toolkit's TreeView... Is there a way to give the new control a default HierarchicalDataTemplate?
Currently, I have the definition of the data template in xaml right along with the the actual control. It should be unnecessary to have to explicitly define the data template everytime since the control will be binding itself to known data types.
Thanks!
JustinAngel
Contributor
4415 points
596 Posts
04-02-2009 11:12 PM |
Yep, that's just plain old Generic.xaml.
1. Create a directory called "tthemes".2. Add a file named "generic.xaml" in it with the following content:
<ResourceDictionary xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
3. Make sure the generic.xaml has a Build Action of Resource and no custom tool.4. Create you TreeView type with a DefaultStyleKey:
public class myTreeView : TreeView
{
public myTreeView()
this.DefaultStyleKey = typeof(myTreeView);
}
5. Set the default ItemTemplate in the generic.xaml file:
xmlns:common="clr-namespace:System.Windows;assembly=System.Windows.Controls"
xmlns:SL_40307_VS="clr-namespace:SL_40307_VS;assembly=SL_40307_VS">
<Style TargetType="SL_40307_VS:myTreeView">
<Setter Property="ItemTemplate">
<Setter.Value>
<common:HierarchicalDataTemplate ItemsSource="{Binding Items}" >
<TextBlock Text="{Binding myString}" />
</common:HierarchicalDataTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
6. Add a TreeView to your page with some data.
<SL_40307_VS:myTreeView x:Name="trv" />
trv.ItemsSource = new ObservableCollection<myItem>()
new myItem("Hello",
new myItem("World"),
new myItem("Foo"),
new myItem("Bar")),
new myItem("Moo",
new myItem("Boo",
new myItem("Goo"))),
};
public class myItem
public myItem(string myString)
this.myString = myString;
public myItem(string myString, params myItem[] myItems)
: this(myString)
ObservableCollection<myItem> itemsObservableCollection = new ObservableCollection<myItem>();
foreach (var item in myItems)
itemsObservableCollection.Add(item);
Items = itemsObservableCollection;
public string myString { get; set; }
public ObservableCollection<myItem> Items { get; set; }
04-06-2009 9:55 AM |
Thank you Justin!