Reputation: 31
I am trying to set different DataTemplates to a ListBox depending on the Pages ActualWidth. In essence I would like to display more data to fill up the empty space.
Since the Item it self defines also is a parameter on what DataTemplate to use I figure I the best way is to use a DataTemplateSelector.
What would be the best way to achieve this since I have found no way of adding a DependencyProperty to a DataTemplateSelector.
Upvotes: 0
Views: 261
Reputation: 69987
When using a DataTemplateSelector
, you get access to the data item that will have the DataTemplate
applied to it. From the DataTemplateSelector
page on MSDN:
public class TaskListDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Task)
{
Task taskitem = item as Task;
if (taskitem.Priority == 1)
return
element.FindResource("importantTaskTemplate") as DataTemplate;
else
return
element.FindResource("myTaskTemplate") as DataTemplate;
}
return null;
}
}
Note how the object item
input parameter is cast to the actual type of the item in the above example. Therefore, you can add a property to your data item class to hold the size information with which you can determine which DataTemplate
to apply.
Upvotes: 0