c# - 不同的 DataTemplate 取决于属性的枚举值

标签 c# wpf xaml data-binding

我想要类似于要求的东西 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/

相关文章:

wpf - 在 WPF TextBox 中禁用覆盖模式(按下 Insert 键时)

c# - 如何删除绑定(bind)到 bool [] 数组的复选框的 Click 处理程序

wpf - 如何在DrawingImage中使用Path?

c# - ASP.NET DropDownList 问题

c# - Xamarin IOS WebClient 在线程中执行

wpf - 检查 WPF 中的重叠形状

.net - 设计模式下的XamlParseExceptions-使设计模式无用

c# - 使用 SyntaxNode.ReplaceNode 替换同一棵树中的多个节点

c# - map 生成器缺乏随机性

.net - Style BasedOn 突然不起作用