我想要类似于要求的东西 here - 但是,我需要模板依赖于一个属性的值,它是一个枚举。
该类看起来与此类似:
class ResultBlock
{
public string Name { get; set; }
public BlockType Type { get; set; }
public IList<ResultBlock> ChildBlocks { get; private set; }
}
BlockType
具有三个不同的值,BLOCK、FILE、FOLDER
- 现在,我想创建一个数据模板以根据值 以不同方式呈现ResultBlock.Type
在当前对象中。
我尝试使用 DataType=
执行此操作,但显然没有用。我确信有一些方法可以仅在 XAML 中非常轻松地执行此操作。
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type docom:ResultBlock}" ItemsSource="{Binding ChildBlocks}">
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<DataTemplate DataType="{x:Type docom:BlockType.BLOCK}">
<TextBlock Text="BLOCK:{Binding Name}" />
</DataTemplate>
</StackPanel.Resources>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
最佳答案
您可以在该属性上触发,例如:
<HierarchicalDataTemplate DataType="{x:Type docom:ResultBlock}"
ItemsSource="{Binding ChildBlocks}">
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding BlockType}" Value="BLOCK">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<!-- Data template for BLOCK blocks -->
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<!-- More triggers -->
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</HierarchicalDataTemplate>
是的,它很冗长。 (您可以将不同类型的模板定义为键控资源,然后在 Setters
中引用它们)
关于c# - 不同的 DataTemplate 取决于属性的枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11465837/