带有 IValueConverter 的图像源的 WPF 依赖项 属性

WPF Dependency Property for Image source with IValueConverter

我打算创建名为 IsPowerOn 的布尔依赖项 属性 的用户控件,当我将其更改为 True 时,PowerOn 图像加载到 Image.source 并且当我将 IsPowerOn 设置为 Fals 时,PowerOff 图像加载到 Image.source.

这是我的用户控件:

<UserControl x:Class="...UcPower"
         ...
<UserControl.Resources>
    <local:PowerBoolean2Image x:Key="PowerBoolean2Image"/>
</UserControl.Resources>
<Grid>
    <Image x:Name="imgPower" Source="{Binding Source, Converter={StaticResource PowerBoolean2Image}, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:UcPower}}}"  />
</Grid>

后面的代码:

    public static readonly DependencyProperty IsPowerOnProperty = DependencyProperty.Register("IsPowerOn", typeof(bool), typeof(UcPower),
     new FrameworkPropertyMetadata(false) { BindsTwoWayByDefault = true });

    public bool IsPowerOn
    {
        get
        {
            return (bool)GetValue(IsPowerOnProperty);
        }
        set
        {
            SetValue(IsPowerOnProperty, value);
        }
    }

和 IValueConverter:

    public class PowerBoolean2Image : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is bool))
        {
            return null;
        }

        if (value.Equals(true))
        {
            // Power On
            return new BitmapImage(new Uri("pack://application:,,,/Resources/Power-On.png"));
        }
        else
        {
            // Power Off
            return new BitmapImage(new Uri("pack://application:,,,/Resources/Power-Off.png"));
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

但我希望它不起作用,我怎么了?

您应该绑定到 IsPowerOn 属性:

<Image Source="{Binding IsPowerOn, ...}" />

而不是

<Image Source="{Binding Source, ...}" />

除此之外,if (value.Equals(true))这个表达式看起来很奇怪。您可以将其替换为

if ((bool)value)
{
    return new BitmapImage(new Uri("pack://application:,,,/Resources/Power-On.png"));
}

return new BitmapImage(new Uri("pack://application:,,,/Resources/Power-Off.png"));

或更短:

return (bool)value
    ? new BitmapImage(new Uri("pack://application:,,,/Resources/Power-On.png"))
    : new BitmapImage(new Uri("pack://application:,,,/Resources/Power-Off.png"));

当我在 IValueConverter 中使用此代码时出现错误:IOException:找不到资源 'resources/power-on.png'。在设计模式下看不到我的表单:

Uri("pack://application:,,,/Resources/Power-On.png")

但是我可以使用程序集名称来解决问题,就像这样的代码:

Uri("pack://application:,,,/ReferencedAssembly;component/Resources/Power-On.png")