有没有办法改变GridViewColumn的CellTemplate在运行时

本文关键字:CellTemplate 运行时 GridViewColumn 改变 有没有 | 更新日期: 2023-09-27 18:13:38

在XAML中,在Windows中。资源,我有2个数据模板

<Window.Resources>
<DataTemplate x:Key="HorribleTemplate">
    (...Horrible Stuff here )
</DataTemplate>
<DataTemplate x:Key="AwesomeTemplate">
    (...Awesome Stuff here )
</DataTemplate>
</Window.Resources>

我创建了一个ListView控件,它默认使用恐怖片模板作为它的CellTemplate。有没有办法改变Listview的CellTemplate到AwesomeTemplate在运行时?

有没有办法改变GridViewColumn的CellTemplate在运行时

当使用触发器时,你需要使用Style设置初始属性值,否则新值不会优先,它将继续使用旧值。这是因为Property值优先。

使用触发器:

<Window x:Class="WpfListBox._32674841.Win32674841"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="Win32674841" Height="300" Width="300">
    <Window.Resources>
        <DataTemplate x:Key="HorribleTemplate" DataType="{x:Type sys:String}">
                <TextBlock Background="CadetBlue" Text="{Binding}"/>
        </DataTemplate>
        <DataTemplate x:Key="AwesomeTemplate" DataType="{x:Type sys:String}">
            <TextBlock Background="Aqua" Text="{Binding}"/>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <Button Content="Change" Click="Button_Click"/>
        <ListView x:Name="ListView1">
            <ListView.Style>
                <Style TargetType="ListView">
                    <Setter Property="ItemTemplate" Value="{StaticResource HorribleTemplate}"/>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="Red"/>
                            <Setter Property="ItemTemplate" Value="{StaticResource AwesomeTemplate}"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ListView.Style>
        </ListView>
    </StackPanel>
</Window>

From code-behind:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace WpfListBox._32674841
{
    /// <summary>
    /// Interaction logic for Win32674841.xaml
    /// </summary>
    public partial class Win32674841 : Window
    {
        public Win32674841()
        {
            InitializeComponent();
            ListView1.ItemsSource = DataStore.Names;
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ListView1.ItemTemplate = (DataTemplate)this.Resources["AwesomeTemplate"];
        }
    }
    public class DataStore
      {
         public static List<String> Names { get { return new List<string>() { "Anjum" }; } }
      }

}