我的任务是制作 DataTemplate 列表,并创建一个用于更改 View 的按钮。 我有“数据”和“足球队”类,还有静态资源。我需要按钮事件的帮助,如何更改当前模板?
作为提示,该示例表示使用此方法:
“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>
最佳答案
我猜你想更改列表框模板,所以,试试这个:
在 XAML 中
<Button Grid.Row="1" Margin="6" Click="changeTemplate">Change View</Button>
在 C# 中
lstTeams.ItemTemplate = (DataTemplate)this.Resources["teamname"];
您必须处理要循环的不同模板,但是,这几乎就是如何在代码隐藏中执行此操作。
关于c# - wpf - 数据模板,使用按钮更改模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16077981/