Windows Phone 动态改变ListBox样式

使用ListBox时通常会借助ItemTemplate帮助我们实现更复杂多样的样式显示,体现了Xaml的灵活。如何动态改变变ListBox的样式,实现类似电脑资源管理器中列表显示和图标显示形式的替换。简单的做法就是将DataTemplate 定义在<phone:PhoneApplicationPage.Resources>,通过C#代码,动态改变ListBox的DataTemplate。

简单实例xaml代码

<phone:PhoneApplicationPage.Resources>
        <DataTemplate x:Key="DataTemplate1">
            <Grid>
                <StackPanel Orientation="Vertical">
                    <TextBlock FontSize="40" Foreground="Yellow" Text="{Binding Text1}"></TextBlock>
                    <TextBlock FontSize="40" Foreground="Yellow" Text="{Binding Text2}"></TextBlock>
                </StackPanel>
            </Grid>
        </DataTemplate>
        <DataTemplate x:Key="DataTemplate2">
            <Grid>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontSize="60" Foreground="Red" Text="{Binding Text1}"></TextBlock>
                    <TextBlock FontSize="60" Foreground="Red" Text="{Binding Text2}"></TextBlock>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </phone:PhoneApplicationPage.Resources>

C#代码,借助Resources["Key"]读取资源中的内容

ObservableCollection<TextCol> TextCols = new ObservableCollection<TextCol>()
            {
                new TextCol(){ Text1="Text1",Text2="Text2" },
                new TextCol(){ Text1="Text3",Text2="Text4" },
                new TextCol(){ Text1="Text5",Text2="Text6" },
                new TextCol(){ Text1="Text7",Text2="Text8" },
            };
            DataTemplate template;
            template = Resources["DataTemplate1"] as DataTemplate;
            list.ItemTemplate = template;
            list.ItemsSource = TextCols;

通过上边简单的几行代码,只要改变Resources中的key值,就能灵活的改变ListBox的样式。

如果样式的定义代码过长,可以通过动态加载Xaml的方式,将DataTemplate的定义放在xaml文件中

注:需有

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

两个命名空间,已字符串的形式加载只需要第一个

StreamResourceInfo sri = Application.GetResourceStream(uri);
            //uri xaml文件路径
            using (StreamReader stream = new StreamReader(sri.Stream))
            {
                temp = stream.ReadToEnd();
            }
            XamlReader.Load(temp);  //返回object对象   

原文地址:https://www.cnblogs.com/my-tzc/p/3466659.html