Silverlight中需要用到模板选择器(DataTemplateSelector)的替代方案
2013-03-30 15:59
465 查看
在WPF下的ListBox,如果我们需要让不同的项根据绑定的值选择不同的数据模板显示,只需要设置ListBox.ItemTemplateSelector属性即可,但在Silverlight下的ListBox控件却没有此属性,因此需要使用另外的方式达到同样的效果。
下面给出了一个在Silverlight中需要用到模板选择器的情况下的替代方案,或者说是解决这类方法的一个新的思路。
那就是使用值转换器(IValueConverter)代替模板选择器(DataTemplateSelector)。
示例代码:SilverlightApplication16.zip
这是我的第一篇博客,有不足之处请见谅。
下面给出了一个在Silverlight中需要用到模板选择器的情况下的替代方案,或者说是解决这类方法的一个新的思路。
那就是使用值转换器(IValueConverter)代替模板选择器(DataTemplateSelector)。
public class TemplateConverter : IValueConverter { public ControlTemplate Template1 { get; set; } public ControlTemplate Template2 { get; set; } private bool flag = false; public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { flag = !flag; if (flag) { return Template1; } else { return Template2; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
<UserControl.Resources> <ControlTemplate TargetType="ContentControl" x:Key="t1"> <TextBlock Text="{Binding}" Foreground="Blue" /> </ControlTemplate> <ControlTemplate TargetType="ContentControl" x:Key="t2"> <TextBlock Text="{Binding}" Foreground="Red" /> </ControlTemplate> <local:TemplateConverter x:Key="TemplateConverter" Template1="{StaticResource t1}" Template2="{StaticResource t2}" /> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <ListBox ItemsSource="{Binding SS}"> <ListBox.ItemTemplate> <DataTemplate> <ContentControl Template="{Binding Converter={StaticResource TemplateConverter}}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
示例代码:SilverlightApplication16.zip
这是我的第一篇博客,有不足之处请见谅。
相关文章推荐
- 项模板选择器属性(ItemTemplateSelector属性)和样式选择器(ItemContainerStyleSelector)
- silverlight 数据模板 DataTemplate 使用 codebehind实现
- 关于c++中模板 T 无法限制的替代方案template< T extends Base>
- Silverlight实用窍门系列:65.Silverlight的数据模板DataTemplate(一)使用数据模板
- 项模板选择器属性(ItemTemplateSelector属性)和样式选择器(ItemContainerStyleSelector)
- Silverlight实用窍门系列:65.Silverlight的数据模板DataTemplate(一)使用数据模板 推荐
- Silverlight实用窍门系列:66.Silverlight的数据模板DataTemplate(二)获取数据模板控件
- Silverlight实用窍门系列:66.Silverlight的数据模板DataTemplate(二)获取数据模板控件
- VisualTreeHelper使用之ListBox模板DataTemplate中CheckBox选中项(WP7.1)
- 实现Windows Phone7 的DataTemplateSelector和CustomDataTemplateSelector
- Silverlight使用DataGrid的模板列(DataGridTemplateColumn)实现类似TreeListView控件的效果
- [Silverlight]HierarchicalDataTemplate层次数据
- 扩展Repeater——让Repeater具有EmptyDataTemplate模板功能!
- WPF之DataTemplate数据模板
- WPF/Silverlight HierarchicalDataTemplate 模版的使用
- silverlight反射代码,需要用到
- Windows 8实用窍门系列:20.Windows 8中的GridView使用(二)和DataTemplateSelector
- silverlight DataGridTemplateColumn 模板列 排序
- [Silverlight学习笔记]如何获取ItemsControl的DataTemplate中定义的控件?
- Silverlight实例秀——可切换视图的DataTemplate(做网站必备技术) 推荐