Search code examples
c#wpfdatatemplate

How to trigger SelectTemplate / How to use ContentTemplateSelector


When using DataTemplateSelector in a WPF application, what kind of user action would trigger DataTemplateSelector.SelectTemple? And what is passed into "object item"?

public class ProductTypeTemplateSelector : DataTemplateSelector
{
    public DataTemplate OrangeTemplate { get; set; }
    public DataTemplate AppleTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item,
      DependencyObject container)
    {
        string product_type = (string)item;
        if (product_type == "orange")
            return OrangeTemplate;
        else
            return AppleTemplate;
    }
}

Question closed. Updated the title to help other rookies like me search.


Solution

  • Let's say your second TabItem needs to show the updated Content depending on the selection. You can place ContentControl in it and bind its Content to the property on VM/code-behind which is tracking the SelectedItem of DataGrid. I am sure you would have bound the SelectedItem of your DataGrid of Tab1 to the property on your ViewModel/code-behind. Let's say that property is SelectedType and is of type string (as apparent from your question).

    Now you just need to bind your ContentControl to this property and apply ContentTemplateSelector:

    <ContentControl Content="{Binding DataContext.SelectedType, RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}" 
                    ContentTemplateSelector="{StaticResource myTemplateSelector}"/>
    

    Here your VM/code-behind containing SelectedType property should implement INotifyPropertyChanged and should raise property change for SelectedType.