I'm creating my own UserControl and I have two different DataTemplates under the UserControl.Resources section in my XAML. I want to choose between these two datatemplates depending on the value of a property on objects displayed in a listview. I do this by creating a custom DataTemplateSelector class and overriding the SelectTemplate method which is supposed to return the DataTemplate I wish to use. However, I have no idea how to "find" my datatemplates that are located in the UserControls resource section, all the examples I've seen only fetches datatemplates from Window.Resources. In this example they fetch the current MainWindow and then use FindResource to find the DataTemplate, how do I fetch my UserControl in a similar manner?:
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
if (item != null && item is AuctionItem)
{
AuctionItem auctionItem = item as AuctionItem;
Window window = Application.Current.MainWindow;
switch (auctionItem.SpecialFeatures)
{
case SpecialFeatures.None:
return
window.FindResource("AuctionItem_None")
as DataTemplate;
case SpecialFeatures.Color:
return
window.FindResource("AuctionItem_Color")
as DataTemplate;
}
}
return null;
}
The example above is from here: ItemsControl.ItemTemplateSelector Property
I usually instantiate my DataTemplateSelector from code behind with the UserControl as parameter in the constructor of the DataTemplateSelector, like so:
public class MyUserControl : UserControl
{
public MyUserControl()
{
Resources["MyDataTemplateSelector"] = new MyDataTemplateSelector(this);
InitializeComponent();
}
}
public class MyDataTemplateSelector : DataTemplateSelector
{
private MyUserControl parent;
public MyDataTemplateSelector(MyUserControl parent)
{
this.parent = parent;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
parent.DoStuff();
}
}
Not the most prettiest girl in town, but it get the job done ;)
Hope this helps!
Try this:
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item != null && item is AuctionItem)
{
AuctionItem auctionItem = item as AuctionItem;
switch (auctionItem.SpecialFeatures)
{
case SpecialFeatures.None:
return
((FrameworkElement)container).FindResource("AuctionItem_None")
as DataTemplate;
case SpecialFeatures.Color:
return
((FrameworkElement)container).FindResource("AuctionItem_Color")
as DataTemplate;
}
}
return null;
}
<DataTemplate x:Key="addTemplate">
<Button Command="{Binding Path=AddCommand}">Add</Button>
</DataTemplate>
<DataTemplate x:Key="editTemplate">
<Button Command="{Binding Path=UpdateCommand}">Update</Button>
</DataTemplate>
<TemplateSelectors:AddEditTemplateSelector
AddTemplate="{StaticResource addTemplate}"
EditTemplate="{StaticResource editTemplate}"
x:Key="addEditTemplateSelector" />
XAML only!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With