条件数据模板 [英] Conditional DataTemplate

查看:29
本文介绍了条件数据模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的.我定义了 2 个数据模板,它们都引用了不同的用户控件.

Here is what I am trying to do. I have 2 Data Templates defined which both refer to a different user control.

<UserControl.Resources>
    <DataTemplate x:Key="myDataTemplate1">
        <Border BorderBrush="Black" BorderThickness="1">
            <myUserControl1 />
        </Border>
    </DataTemplate>
    <DataTemplate x:Key="myDataTemplate2">
            <Border BorderBrush="Black" BorderThickness="1">
                <myUserControl2/>
            </Border>
    </DataTemplate>
</UserControl.Resources>

我使用这些数据模板来显示使用 ItemsControl 的项目列表,如下所示:

I am using these Data Templates to display a list of items using ItemsControl like this:

<ItemsControl x:Name="myItemList" ItemTemplate="{StaticResource myDataTemplate1}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate />
    </ItemsControl.ItemsPanel>
</ItemsControl>

我希望 ItemTemplate 有条件地为 myDataTemplate1 或 myDataTemplate1,具体取决于整数变量的值分别为 1 或 2.

I would like the ItemTemplate to conditionally be either myDataTemplate1 or myDataTemplate1 depending on the value of an integer variable being 1 or 2 respectively.

我应该为此使用 DataTriggers 还是有其他方法可以做到这一点?感谢您的帮助.

Should I use DataTriggers for this or is there another way to do this? Appreciate the help.

推荐答案

不要设置 ItemTemplate 而是使用 ItemTemplateSelector.

Don't set the ItemTemplate but use an ItemTemplateSelector.

DataTriggers 当然也可以,为选择器省去额外的类.例如

DataTriggers would be fine too of course, spares you the extra class for the selector. e.g.

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <ContentControl Content="{Binding}">
            <ContentControl.Style>
                <Style TargetType="ContentControl">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ThatProperty}" Value="1">
                            <Setter Property="ContentTemplate"
                                    Value="{StaticResource myDataTemplate1}" />
                        </DataTrigger>
                        <DataTrigger Binding="{Binding ThatProperty}" Value="2">
                            <Setter Property="ContentTemplate"
                                    Value="{StaticResource myDataTemplate2}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentControl.Style>
        </ContentControl>
    </DataTemplate>
</ItemsControl.ItemTemplate>

这篇关于条件数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆