c# - 基于布尔值的按钮的 C# WPF 图像转换器
问题描述
我正在用 WPF 和 C# 制作 RPG。我有附有图像的移动按钮。我试图弄清楚如何根据是否有可用的房间朝那个方向移动来更改按钮的图像。我已经查找了转换器,但我不太确定如何根据我的情况实施它们。
这是我在网上找到的一个尝试实现的示例:
<Button Content="{Binding MyBooleanValue, Converter={StaticResource
MyBooleanToImageConverter}}" />
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
bool v = (bool)value;
Uri path = new Uri((v ? "ImgSrcIfTrue.png" : "ImgSrcIfFalse.png"), UriKind.Relative);
return new Image()
{
Source = new System.Windows.Media.Imaging.BitmapImage(path),
Height = ...,
Width = ...,
};
}
这是我正在处理的代码的一部分
<!-- Movement Buttons -->
<Button Grid.Row="1" Grid.Column="1"
Click="OnClick_MoveNorth">
<StackPanel>
<Image Source= "/Image/Buttons/Up.png"/>
</StackPanel>
</Button>
我已经有了布尔值的函数,我只是想弄清楚如何实现一个转换器来更改按钮图像。
我使用了布尔可见性并希望做类似的事情。
Visibility="{Binding HasMonster, Converter={StaticResource BooleanToVisibility}}"
解决方案
在 Button 的 Content 中更好地绑定 Image 元素的 Source 属性:
<Button>
<Image Source="{Binding MyBooleanValue,
Converter={StaticResource MyBooleanToImageConverter}}"/>
</Button>
转换器将直接返回一个 BitmapImage。如果图像文件应该是程序集资源(即它们是 Visual Studio 项目的一部分,并且它们的 Build Action 设置为 Resource),则必须从 Pack URI 加载它们:
public class BooleanToImageConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
var uri = (bool)value
? "pack://application:,,,/ImgSrcIfTrue.png"
: "pack://application:,,,/ImgSrcIfFalse.png";
return new BitmapImage(new Uri(uri));
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
您可以像这样将转换器添加到 Window 的资源中:
<Window.Resources>
<local:BooleanToImageConverter x:Key="MyBooleanToImageConverter"/>
...
</Window.Resources>
推荐阅读
- html - XHTML2FO.xsl 在转换为 PDF 时为嵌套的 html 表格标签提供错误
- java - 如何返回包含 xs 和 ys 的所有点的列表。在java中使用流时?
- vb.net - 我怎样才能让计时器越来越慢,直到它停止?
- pytorch - PyTorch Geometric 如何输入一个样本而不是小批量?
- inheritance - 部分定义函数的名称“如果存在”,可以继承的“像抽象”是什么?
- r - tf_idf 单词和结果矩阵之间的不匹配
- javascript - 将变量从Flask传递给JavaScript而不刷新页面?
- postgresql - 这个查询可以进一步优化吗?即使在较差的硬件上也可以使其快速运行吗?
- c# - Cefsharp WPF C# Count not Find File(s) after cleaning solution
- node.js - 在猫鼬中使用 $lookup 时无法获得所需的结果