wpf - 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>
解决方案
您可以使用该元素将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>
推荐阅读
- java - 识别文本区域对象中的 KeyListener 继承
- mysql - 如何调用具有值匹配的 mysql in 子句?
- r - 用另一列替换一列的值
- python - 通过子进程访问maya内部的环境变量
- jquery - 如何修复引导轮播错误?
- parsing - Regex 和 decimal.TryParse 无法测试小数
- python - 程序在使用“elif”时起作用,但在将“elif”替换为“if”时不起作用。我很难弄清楚为什么?(Python)
- python - Pickled 模型实例的 Django 版本 3.0.3 与当前版本 3.0.7 不匹配
- dotnetnuke - DNN 模块安装
- c# - 如何为只读文本框设置字符限制?