【问题标题】:WPF SVG image binding using a converter使用转换器的 WPF SVG 图像绑定
【发布时间】:2019-03-20 12:33:55
【问题描述】:

我想更改我的图片来源:

<Image Source="{svg:SvgImage image.svg}"/>

对于在枚举属性上使用绑定的东西:

XAML:

<Resources>
    <local:MyConverter x:Key="MyConverter" />
</Resources>    

<Image Source="{svg:SvgImage Binding MyEnumProperty, Converter={StaticResource MyConverter}}" />

后面的代码:

public enum MyEnum 
{
    Value1,
    Value2
}

public class MyConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var myValue = (MyEnum)(value);
        switch (myValue)
        {
            case MyEnum.Value1:
                return "image1.svg";
            case MyEnum.Value2:
                return "image2.svg";
            default:
                throw new NotImplementedException();
        }
    }

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

这不起作用,我怀疑这与 svg:SvgImageBinding MyEnumProperty 组合在同一个语句中有关。

我收到以下错误:

The member "Converter" is not recognized or is not accessible.

The property 'Converter' was not found in type 'SvgImageExtension'.

问题: 这样做的正确方法是什么?

【问题讨论】:

    标签: c# wpf svg binding ivalueconverter


    【解决方案1】:

    表达式

    {svg:SvgImage Binding MyEnumProperty ...}
    

    不是有效的 XAML,而且因为 SvgImage 是一个标记扩展,所以不能绑定它的属性。

    但是,您可以在图像样式中使用 DataTriggers 而不是与转换器绑定:

    <Image>
        <Image.Style>
            <Style TargetType="Image">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding MyEnumProperty}" Value="Value1">
                        <Setter Property="Source" Value="{svg:SvgImage image1.svg}"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding MyEnumProperty}" Value="Value2">
                        <Setter Property="Source" Value="{svg:SvgImage image2.svg}"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>
    

    【讨论】:

    • 是否可以使数据触发器动态化?如果我有另一个属性 MyOtherEnumProperty 并且我想为它使用相同的触发器,我可以更改数据触发器来处理这两个属性吗?
    猜你喜欢
    • 2014-05-29
    • 2015-09-25
    • 2012-04-15
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 2010-10-15
    相关资源
    最近更新 更多