xaml中的TemplateSelector

本文介绍了如何在WPF中使用RadComboBox结合自定义的ItemTemplateSelector实现动态选择模板的方法。通过具体的XAML代码示例和资源文件说明了如何根据不同条件显示不同样式的项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态选择Template

经常在某个控件中看到xxxSelecter,下面以RadComBox举例介绍:

首先上xaml代码:

        <telerik:RadComboBox x:Name="searchCombo" 
                            IsEditable="True" 
                            OpenDropDownOnFocus="False" 
                            EmptyText="Search" 
                            ItemsSource="{Binding SearchResults}"
                            Margin="50,0,0,0" 
                            SelectedItem="{Binding SearchItem, Mode=TwoWay}"
                            ItemTemplateSelector="{StaticResource SearchComboBoxItemTemplateSelector}">
        </telerik:RadComboBox>
XAML

资源文件:

         <!--SEARCH COMBO-->
        <DataTemplate x:Key="EmperorItemTemplate">
            <Grid HorizontalAlignment="Stretch" Margin="2">
                <TextBlock Text="{Binding Text}" Foreground="Red" FontSize="13" FontFamily="Arial" HorizontalAlignment="Left" VerticalAlignment="Center"  Margin="6,0,0,0"/>
            </Grid>
        </DataTemplate>

        <DataTemplate x:Key="CounselorItemTemplate">
            <Grid Margin="2">
                <TextBlock Text="{Binding Text}" Margin="25,0,0,0" FontSize="11" Foreground="Black" FontFamily="Arial" VerticalAlignment="Center"/>
            </Grid>
        </DataTemplate>

<local:SearchComboBoxItemTemplateSelector x:Key="SearchComboBoxItemTemplateSelector" 
            EmperorItemTemplate="{StaticResource EmperorItemTemplate}"
            CounselorItemTemplate="{StaticResource CounselorItemTemplate}"/>
Resources

资源选择器:

 public class SearchComboBoxItemTemplateSelector : DataTemplateSelector
    {
        public DataTemplate EmperorItemTemplate { get; set; }

        public DataTemplate CounselorItemTemplate { get; set; }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            //根据传进来的item进行业务逻辑判断,不同的逻辑对应不同的    ItemTemplate 
        }
    }
样式判断
资源文件中的两个属性local:CounselorItemTemplate,local:EmperorItemTemplate即对应资源选择器中的两个属性。

 

 

转载于:https://www.cnblogs.com/luqixinhe/p/3230026.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值