How can I use predefined headers inside a Silverlight treeview for each item?
For my Silverlight TreeView
's items source I have a collection of Order
items, and each Order
has two collections, OrderItems
and Commissions
. So I want a treeview that looks kind of like
Order #1
- Order Items
- Order Item #1
- Order Item #2
- Order Item #3
- Commissions
- Commission #1
- Commission #2
- Commission #3
- Commission #4
etc. So ever Order will have a Order Items and Commissions header, and the contents of these are databound. I'm kind of stumped by this, even though it seems kind of simple.
This is the XAML I have 开发者_开发技巧so far. Obviously creating the HierarchicalDataTemplate
s for the OrderItems
and CommissionsItems
collections is simple, but how do I set the ItemsSource
of the HDT above? In other words, what would [what goes here?] look like?
<Grid>
<Grid.Resources>
<sdk:HierarchicalDataTemplate
x:Key="OrdersTreeLevel0"
ItemsSource="{StaticResource [what goes here?]}"
ItemTemplate={StaticResource OrdersTreeLevel1}">
<TextBlock
FontWeight="{Binding IsUnread}"
Text="{Binding Id, StringFormat='Order #{0}'}" />
</sdk:HierarchicalDataTemplate>
</Grid.Resources>
<sdk:TreeView
ItemsSource="{Binding Items}"
ItemTemplate="{StaticResource OrdersTreeLevel0}">
</sdk:TreeView>
</Grid>
You'll need a value converter for this to take an Order
object and convert it to an array of a type that carries Name
and Items
properties:-
public class ItemWrapper
{
public string Name {get; set; }
public IEnumerable Items {get; set;}
}
public class OrderConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Order order = value as Order;
if (order != null)
{
List<object> result = new List<object>();
result.Add(new ItemWrapper() {Name = "Order Items", Items = order.OrderItems} );
result.Add(new ItemWrapper() {Name = "Commission Items", Items = order.CommissionItems} );
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now you add this converter to your resources and reference it in your template:-
<Grid.Resources>
<local:OrderConverter x:Key="OrderConverter" />
<sdk:HierarchicalDataTemplate
x:Key="OrdersTreeLevel0"
ItemsSource="{Binding Converter=OrderConverter}"
ItemTemplate={StaticResource OrdersTreeLevel1}">
<TextBlock
FontWeight="{Binding IsUnread}"
Text="{Binding Id, StringFormat='Order #{0}'}" />
</sdk:HierarchicalDataTemplate>
</Grid.Resources>
Of course thats the easy bit, the really tricky bit is if you need a different template for Commission
and OrderItem
. If these both have simple properties in common such as Name then a single template for level2 will suffice. Otherwise things get more complicated.
精彩评论