【问题标题】:Value Converter Without Binding On Image Source - conversion不绑定图像源的值转换器 - 转换
【发布时间】:2011-06-13 16:24:54
【问题描述】:

我在视图中的图像源上绑定来自视图模型类的字符串属性。字符串属性的值可以是男人的值 1,女人的值是 2。我还在绑定上使用转换器,它返回图像源的 uri。

鉴于我有这个:

    <Image Style="{StaticResource InfoIcon}" 
           Source="{Binding ., Mode=OneWay,UpdateSourceTrigger=PropertyChanged,
                Converter={StaticResource sexImgConverter}, 
                ConverterParameter=Oponent.Info.Sex}"/>

转换器方法在这里:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        const string woman = "/images/icons/chat/woman.png";
        const string man = "/images/icons/chat/man.png";

        string result = string.Empty;

        string result = int.Parse(value.ToString()) == 1 ? man : woman;

        return new Uri(result);
    }

问题是我绑定属性sex(在Oponent.Info.Sex 视图中),它是字符串类型并解析为整数。

但是如果我在线添加调试器断点:

string resul = int.Parse(value.ToString()) == 1 ? man : woman;

我看到该值是我的视图模型类的类型。

我尝试使用这个转换方法,没有其他绑定,就是这样:

<TextBlock Style="{StaticResource InfoText}">
     <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}, {1} rokov">
            <Binding Path="Oponent.Info.Sex" Converter="{StaticResource sexConverter}"/>
            <Binding Path= "Oponent.Info.Age"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

我使用相同的转换器在线添加调试器断点:

string resul = int.Parse(value.ToString()) == 1 ? man : woman;

我看到值是字符串类型。

我做错了什么?

【问题讨论】:

    标签: wpf image binding converter


    【解决方案1】:

    您似乎对 Binding 的不同部分与 Convert 方法参数之间的关系感到困惑。这是 IValueConverter.Convert 的方法签名:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    

    value 参数来自绑定的值,通常直接分配给目标属性。在您的情况下,您的 Binding 使用 {Binding .}(仅相当于 {Binding}),它使用当前 DataContext 作为源,并且没有指定路径,因此导致 DataContext 对象作为您的值(在这种情况下是您的 View Model 类)。

    Binding 中设置的 ConverterParameter 在 Convert 方法中显示为 parameter 参数。这不是绑定值,需要是某种类型的固定值:字符串、x:Static 对象引用、StaticResource 等。您声明 Binding 的方式很可能被解析为字符串:“Oponent. Info.Sex",您应该在断点处看到 Convert 方法中的 parameter

    您在 MultiBinding 中使用的绑定是在正确的位置使用参数。试试这个来代替你的 Source 绑定(你的 Mode 和 UpdateSourceTrigger 设置是不需要的):

    Source="{Binding Path=Oponent.Info.Sex, Converter={StaticResource sexImgConverter}}"
    

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 2012-03-27
      相关资源
      最近更新 更多