2013-04-18 56 views
2

我的任務是製作DataTemplate列表,並創建一個用於更改視圖的按鈕。 我有「數據」和「足球隊」類,也有靜態資源。我需要按鈕事件的幫助,如何更改當前模板?wpf - 數據模板,用按鈕更改模板

作爲尖,例如說,使用這種方法:

「this.Resources [資源鍵]作爲數據類型;」

的XAML:

<Window x:Class="WpfApplication11.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" 
     Height="250" 
     Width="300"> 
    <Window.Resources> 
    <DataTemplate x:Key="teamName"> 
     <TextBlock FontWeight="Bold" 
       Text="{Binding Path=TeamName}"></TextBlock> 
    </DataTemplate> 
    <DataTemplate x:Key="year"> 
     <TextBlock Text="{Binding Path=FoundingYear}"></TextBlock> 
    </DataTemplate> 
    <DataTemplate x:Key="logo"> 
     <Image Source="{Binding Path=Image}" /> 
    </DataTemplate> 

    </Window.Resources> 
    <Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*" /> 
     <RowDefinition Height="Auto" /> 
    </Grid.RowDefinitions> 
    <ScrollViewer Grid.Row="0" 
        AllowDrop="True"> 
     <ListBox Name="lstTeams"> 

     </ListBox> 
    </ScrollViewer> 
    <Button Grid.Row="1" 
      Margin="6">Change View</Button> 
    </Grid> 
</Window> 
+0

看看我對類似問題的回答。它演示瞭如何使用按鈕和數據類型更改視圖http://stackoverflow.com/a/15960843/1862333 – failedprogramming

回答

2

我猜你想改變列表框模板的話,試試這個:

在XAML

<Button Grid.Row="1" Margin="6" Click="changeTemplate">Change View</Button> 

在C#

lstTeams.ItemTemplate = (DataTemplate)this.Resources["teamname"]; 

你必須處理不同的t你想循環使用模板,但是這非常類似於如何執行代碼隱藏。

+0

這對我有效。謝謝! – Spencer