首页 > 解决方案 > 基于布尔值的按钮的 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}}"

标签: c#wpf

解决方案


在 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>

推荐阅读