2015-09-20 146 views
1

在XAML中,內部Windows.Resources,我有2個的DataTemplate有沒有辦法在運行時更改GridViewColumn的CellTemplate?

<Window.Resources> 

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

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

</Window.Resources> 

我創建ListView控件,其默認使用HorribleTemplate其CellTemplate。有沒有辦法在運行時將ListView的CellTemplate更改爲AwesomeTemplate?

+0

是有幾種方法。改變它的觸發器是什麼?一個事件,數據值? –

+0

@GlenThomas事件,先生。 – Wahyu

回答

1

在使用觸發器時,您需要使用樣式設置初始屬性值,否則新值不會優先,並且會繼續使用舊值。發生這種情況是因爲屬性值優先。

使用觸發器:

<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> 

從後臺代碼:

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" }; } } 
     } 


} 
+0

看起來很有希望!我將在稍後嘗試一個問題,我可以在'內放置多於1個''嗎? – Wahyu

+0

是的,你可以有多個觸發器。試試你自己吧。 – AnjumSKhan

+0

Thx!有效! – Wahyu

相關問題