c# - 当选择选项卡时,如何更改 TabControl 的 TabItem 标题上的图像?

标签 c# wpf xaml

我在窗口中有以下 TabControl,当这些选项卡时,我需要将图像分别更改为“awb-white.png”和“center-weighted-white.png”被选中。 (当未选择它们时返回 -white)。解决这个问题的最佳方法是什么?可以在 XAML 中完成吗?

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <TabControl>
        <TabItem>
            <TabItem.Header>
                <Image Source="images/awb-black.png" Stretch="None" />
            </TabItem.Header>
            <Grid />
        </TabItem>
        <TabItem>
            <TabItem.Header>
                <Image Source="images/center-weighted-black.png" Stretch="None" />
            </TabItem.Header>
            <Grid />
        </TabItem>
    </TabControl>
</Window>

我是 WPF 的新手,因此详细信息会有很大帮助。

最佳答案

使用带有默认 setter 的 Style header ,在 IsSelected 上添加 Trigger 并为新 header 创建另一个 setter 。

<TabItem>
    <TabItem.Style>
         <Style TargetType="TabItem">
              <Setter Property="Header">
                  <Setter.Value>
                      <Image ...>
                  </Setter.Value>
              </Setter>
              <Style.Triggers>
                  <Trigger Property="IsSelected" Value="True">
                      <Setter Property="Header">
                          <Setter.Value>
                              <Image ...>
                          </Setter.Value>
                      </Setter>
                  </Trigger>
              </Style.Triggers>
         </Style>
    </TabItem.Style>
</TabItem>

由于这相当冗长,您可能希望从 TabItem 继承并将其放入默认的 template 中,其中 Image.Sourcesbound 的两个自定义属性,然后您只需要在您的实例上设置这些即可。

另请注意,由于 precedence ,默认值位于 setter 中这一事实很重要,如果直接设置它,触发器将不会覆盖该值。

关于c# - 当选择选项卡时,如何更改 TabControl 的 TabItem 标题上的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8774887/

相关文章:

C#的编译器设计——前向引用

c# - TextBlock 上的删除线效果

wpf - 在 XAML 中绑定(bind)到 AssemblyVersion(用于帮助/关于对话框)

c# - 单击 DataGridCell 时的 WPF 触发事件

WPF 列表框 dataContextChanged

wpf - 如何在 WPF 组合框中为下拉列表值/所选项目显示不同的值?

WPF 自定义 TabControl

c# - Linq:将 memberExpression 类型转换为不可空

c# - 适用于 Windows Phone 的 Microsoft TPL 数据流

c# - 保存 XmlDocument 时,它会忽略 XmlDeclaration (UTF8) 中的编码并使用 UTF16