Wpf 我想在另一个datatemplate中按类型模板化对象属性

Wpf 我想在另一个datatemplate中按类型模板化对象属性,wpf,Wpf,我有一个DataGrid的视图模型,如下所示: public class Cell { public CellValue CellValue { get; } } <DataTemplate DataType="{x:Type viewModel:Cell}"> <Grid> <DataTemplate DataType="{x:Type viewModel:CellValue}"> <TextB

我有一个DataGrid的视图模型,如下所示:

public class Cell
{
    public CellValue CellValue { get; }
}
<DataTemplate DataType="{x:Type viewModel:Cell}">
    <Grid>
        <DataTemplate DataType="{x:Type viewModel:CellValue}">
            <TextBlock Text="{Binding Value}"/>
        </DataTemplate>
    </Grid>
</DataTemplate>
CellValue属性可以有几种类型:

public class CellValue
{
    public double Value { get; }
}

public class TwoValueCell : CellValue
{
    public double Value2 { get; }
}
DataGrid正在将ItemsSource绑定到我的行和单元格列表

DataGrid按预期绑定数据:我在每个DataGridCell中获得一个单元格。因此,我在参考资料中有这样一种风格(目前为本地参考资料):


我喜欢将模板绑定到视图模型类型

问题是:我不想在TextBlock上绑定,而是想在那里扩展另一个DataTemplate,我可以通过特定的CellValue类型再次定义它

换句话说,在psudocode中,它可能如下所示:

public class Cell
{
    public CellValue CellValue { get; }
}
<DataTemplate DataType="{x:Type viewModel:Cell}">
    <Grid>
        <DataTemplate DataType="{x:Type viewModel:CellValue}">
            <TextBlock Text="{Binding Value}"/>
        </DataTemplate>
    </Grid>
</DataTemplate>

但我需要在某处定义特定的CellValue数据模板

底线是DataGridCell有一个类型,并且有一个数据模板,但是在单元格的属性上有几个特定的类型,我想根据属性的实际类型定义自定义数据模板


有什么帮助吗?

您可以使用ContentControl

<DataTemplate ...>
    <Grid>
       <ContentControl DataContext="{Binding SomeProperty}">
         <ContentControl.ContentTemplate>
           <DataTemplate ...>  ...  </DataTemplate>
         </ContentControl.ContentTemplate>
       </ContentControl>
    </Grid>
</DataTemplate>

...  

是!我刚才试过了,它正在工作!它也在使用嵌套数据模板上的自定义类型。。。