动态选择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>
资源文件:
<!--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}"/>
资源选择器:
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即对应资源选择器中的两个属性。
出处:http://www.cnblogs.com/luqixinhe/
作者:许欣欣
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。