Silverlight中需要用到模板选择器(DataTemplateSelector)的替代方案

在WPF下的ListBox,如果我们需要让不同的项根据绑定的值选择不同的数据模板显示,只需要设置ListBox.ItemTemplateSelector属性即可,但在Silverlight下的ListBox控件却没有此属性,因此需要使用另外的方式达到同样的效果。

下面给出了一个在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

这是我的第一篇博客,有不足之处请见谅。

原文地址:https://www.cnblogs.com/fjicn/p/2990486.html