In WPF how to define a Data template in case of enum?

后端 未结 3 1762
感情败类
感情败类 2021-01-13 20:38

I have a Enum defined as Type

public Enum **Type**
{
   OneType,
   TwoType,
   ThreeType
};

Now I bind Type to a drop dow

相关标签:
3条回答
  • 2021-01-13 20:57

    It's very often the case that people use enums when they should be using polymorphism. You should, at the least, check to see if this is one of those cases. The presence of switch blocks in your class's code that check the value of the instance's enum is often a sign that this is a good idea. If you can eliminate the enum by defining subclasses, then you don't have to mess around with the likes of data template selectors and value converters.

    0 讨论(0)
  • 2021-01-13 21:10

    One way to do it would be to create a DataTemplateSelector, and assign it to the ItemTemplateSelector property of the menu. In the code of the DataTemplateSelector, you just need to return a DataTemplate based on the enum value

    0 讨论(0)
  • 2021-01-13 21:10

    Not sure whether this is an applicable solution to your particular situation, but it is relevant to the question of DataTemplate for enum. It is possible to create one DataTemplate for the enum type and use DataTriggers to tweak the controls in that template for individual enum value:

    Enum:

    enum MyEnumType 
    {
        ValueOne,
        ValueTwo,
    }
    

    Template:

    <DataTemplate DataType="{x:Type MyEnumType}">
        <TextBlock x:Name="valueText"/>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding}" Value="{x:Static MyEnumType.ValueOne}">
                <Setter TargetName="valueText" Property="Text" Value="First Value" />
            </DataTrigger>
            <DataTrigger Binding="{Binding}" Value="{x:Static MyEnumType.ValueTwo}">
                <Setter TargetName="valueText" Property="Text" Value="Second Value" />
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
    
    0 讨论(0)
提交回复
热议问题