首页 > 解决方案 > C# WPF 使用带有 Button.Tag 的多图像源 ControlTemplate

问题描述

我在 Button 中使用 ControlTemplate 时遇到问题。我想创建一个带有图像和文本的按钮。当鼠标悬停在按钮上时,图像会发生变化。我使用 Button.Tag 来传递图像源。但我需要传递两个图像源。是否可以在 Button.Tag 中创建图像源列表并在 ControlTemplate 中选择?谢谢。

<Style x:Key="myBtnStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <StackPanel Orientation="Horizontal">
                    <Image x:Name="myImg" Source="{TemplateBinding Tag[0]}" HorizontalAlignment="Left"/>
                    <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Left"/>
                </StackPanel>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="myImg" Property="Source" Value="{TemplateBinding Tag[1]}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Button Content="Click" Style="{StaticResource myBtnStyle}">
    <Button.Tag>
      <ImageSource>/img/usb_white.png</ImageSource>
      <ImageSource>/img/usb_gray.png</ImageSource>
    </Button.Tag>
</Button>    

标签: wpfwpf-controlscontroltemplate

解决方案


您可以使用该元素将Tag属性设置为:ImageSource[]<x:Array>

<Button Content="Click" Style="{StaticResource myBtnStyle}">
    <Button.Tag>
        <x:Array Type="ImageSource">
            <BitmapImage UriSource="Images/Buldingimage2.jpeg" />
            <BitmapImage UriSource="Images/words.jpg" />
        </x:Array>
    </Button.Tag>
</Button>

您还需要将TemplateBindings模板中的 替换为以下内容的绑定TemplatedParent

<Style x:Key="myBtnStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <StackPanel Orientation="Horizontal">
                    <Image x:Name="myImg" Source="{Binding Tag[0], RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Left"/>
                    <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Left"/>
                </StackPanel>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="myImg" Property="Source" Value="{Binding Tag[1], RelativeSource={RelativeSource TemplatedParent}}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

推荐阅读