如何在XAML中更改ToggleButton的自定义内容

4
我已经在一个 ResourceDictionary 中更改了一个 ToggleButton 的样式。在我的样式中,我更改了 ToggleButtonControlTemplate 并在 Content 之前放置了一张图片。 现在我的问题是:对于我在 XAML 中使用的不同 ToggleButtons,需要更改该图片。我应该为每个 ToggleButton 定义不同的样式并分别设置不同的图片,还是有一种方法可以在 XAML 中更改其图片?
<Style x:Key="BaseToggleButton" TargetType="ToggleButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
                <StackPanel Orientation="Horizontal" x:Name="Border">
                    <Image Width="13" Height="13" Source="{StaticResource ColumnsLayoutMiniIcon}"/>
                    <TextBlock>
                        <ContentPresenter/>
                    </TextBlock>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

有没有办法我可以在这里更改图片而不是在样式中更改?
<RadioButton Content="Plan View"
             GroupName="View"
             Style="{StaticResource BaseToggleButton}">
</RadioButton>

1
<TextBlock> <ContentPresenter/> </TextBlock> - 这里有些问题。 - Federico Berasategui
@HighCore 我已经删除了一些样板代码。我可能意外地删除了一些东西。但是这个想法是如何在仅更改图像时重用整个样式。 - Vahid
1个回答

4

当然,你可以利用一个称为Tag的未使用属性,它非常适合这种情况,你可以使用它来传递你的图像路径或资源声明等,一旦我们将其绑定到模板上,就像这样:

<Style x:Key="BaseToggleButton" TargetType="ToggleButton">
    <!-- Let's give it a default -->
    <Setter Property="Tag" Value="{StaticResource ColumnsLayoutMiniIcon}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
                <StackPanel Orientation="Horizontal" x:Name="Border">
                    <Image Width="13" Height="13" 
                           Source="{TemplateBinding Tag}"/>
                    <ContentPresenter/>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

现在我们可以保持原样,它会显示您的默认小图标,或者您可以在实例级别指定一个新的,比如:

<ToggleButton Content="Plan View"
              Tag="{StaticResource ADifferentImagePathOrResourcePointingToOne}"
              Style="{StaticResource BaseToggleButton}"/>

希望这能有所帮助,祝好。

非常棒的想法!非常感谢。这肯定会帮助我以不同的方式思考其他一些问题。 - Vahid
1
很高兴你找到了解决方法,当你学到新东西的时候总是美好的一天。 :) - Chris W.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接