ContentControl with DataTemplateSelector - help needed

不羁岁月 提交于 2019-11-30 20:32:09

The solution was not very hard....

 DataContext="{Binding RelativeSource={RelativeSource AncestorType=ContentControl},Path=DataContext}"

In this way the context of template is the same with the content of his parent and I can acces his members. I think I tryind to do that but I didn't code correct... Thanks Cstein for involving !

If I understand you right you want to create your DataTemplate inside the templateselector, while the datatemplate is based on the editedModel property.

I would solve this problem this way:

Windows.xaml:

<Window.Resources>
    <local:Selector x:Key="sel"/>

    <DataTemplate x:Key="templateA">
        <TextBlock Text="{Binding editedModel.PropertyName}"/>
    </DataTemplate>

    <DataTemplate x:Key="templateB">
        <TextBlock Text="{Binding editedModel.PropertyName}"/>
    </DataTemplate>

    <DataTemplate x:Key="templateC">
        <TextBlock Text="{Binding editedModel.PropertyName}"/>
    </DataTemplate>

</Window.Resources>

Contentcontrol and listbox stay the same.

DataTemplateSelector:

public class Selector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is ClassA)
            return (container as FrameworkElement).FindResource("TemplateA") as DataTemplate;
        else if (item is ClassB)
            return (container as FrameworkElement).FindResource("TemplateB") as DataTemplate;
        else if (item is ClassC)
            return (container as FrameworkElement).FindResource("TemplateC") as DataTemplate;
        return null;
    }
}

This return an existing datatemplate depending on the item's type. I hope I understood you right and it helps you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!