c# - wpf - 数据模板,使用按钮更改模板

标签 c# wpf xaml

我的任务是制作 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/

相关文章:

c# - 如何在不实际单击按钮的情况下触发 Button Click 事件?

c# - 使用C#在页面上编写ASP代码

c# - 如何在控件之间添加动态间距? (附图片)

c# - 检查密码字段是否为空

c# - 数组上的 AsEnumerable() 有什么用?

c# - Word 加载项中的绑定(bind)用法

c# - WPF MVVM 关闭窗口

c# - 使用 WebBrowser-Control 在 WPF 中显示本地 PDF 文件

c# - ContentControl 旋转装饰器渲染

wpf - 在标签上显示标准文本?