【发布时间】:2019-10-10 08:20:54
【问题描述】:
我在 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>
【问题讨论】:
-
请不要使用
Tag。它没有描述性名称(因此它会令其他开发人员感到困惑)并且您无法控制它的数据类型。您可以改为创建attached property。
标签: wpf wpf-controls controltemplate