具有IValueConverter的图像源的WPF依赖属性

时间:2016-01-31 19:48:49

标签: wpf dependency-properties ivalueconverter

我打算使用名为IsPowerOn的布尔依赖属性创建Usercontrol,当我更改它时,PowerOn图像加载到Image.source,当我将IsPowerOn设置为Fals时,PowerOff图像加载到Image.source。

这是我的UserControl:

<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();
    }
}

但是我觉得它不起作用,我怎么了?

2 个答案:

答案 0 :(得分:2)

您应该绑定到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"));

答案 1 :(得分:0)

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

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

但是我可以使用汇编名来解决这个代码的问题:

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