【问题标题】:Firing PropertyChanged event when data is bound without path无路径绑定数据时触发 PropertyChanged 事件
【发布时间】:2014-06-24 13:33:10
【问题描述】:

我有一个绑定到 ImageMetadata 类的 ObservableCollection 的列表框。 Listbox 的项模板定义为

<Image Source="{Binding Converter={StaticResource ImageConverter}}" />

ImageConverter 写成

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var metadata = (ImageMetadata)value;
        if (metadata.IsPublic)
        {
            //code to return the image from path
        }
        else
        {
            //return default image
        }
     }

ImageMetadata 是“模型”类,写成

class ImageMetadata : INotifyPropertyChanged
{
    public string ImagePath
    {
        ......
    }

    public bool IsPublic
    {
        ......
    }
}

当图像更新时,我将触发 PropertyChanged 事件,如下所示

NotifyPropertyChanged("ImagePath");

这里的问题是: NotifyPropertyChanged 事件将不起作用,因为我将更改的属性名称指定为“ImagePath”并且绑定到“ImageMetadata”对象而不是'ImagePath' 属性。

不能使用

<Image Source="{Binding ImagePath, Converter={StaticResource ImageConverter}}" />

因为我还需要 IsPublic 属性来决定显示哪个图像。

如何修改代码以正确触发 PropertyChanged 事件?

编辑:我正在为 Windows phone 8 开发。

【问题讨论】:

  • 之前有一个similar question。看看有没有帮助。
  • Style 是如何设置你的 Source 属性的,在样式内部你可以使用 DataTriggers 来定义当 ImagePath 发生变化时会发生什么。
  • 您也可以采用 MVVM 方式并添加一个视图模型类(可能派生自您的 ImageMetadata 模型类),它通过另一个属性提供图像。
  • @Clemens,你能解释一下吗?你也看过icebat在上面的评论吗?你推荐类似的东西吗?
  • 您可以添加另一个属性,该属性以类似于转换器的方式返回图像。但是,您可能不希望在模型类中拥有此属性,因此您可以将它放在“中间”类中,即所谓的视图模型中。您可以在网上搜索 MVVM 以获取有关此模式的更多信息,该模式已成为 WPF、Silverlight 和 Windows Store 应用程序中的标准架构模式。

标签: c# .net wpf xaml windows-phone-8


【解决方案1】:

您可以将MultiBinding 与多值转换器一起使用:

<Image>
    <Image.Source>
        <MultiBinding Converter="{StaticResource ImageConverter}">
            <Binding Path="ImagePath"/>
            <Binding Path="IsPublic"/>
        </MultiBinding>
    </Image.Source>
</Image>

Convert 方法如下所示:

public object Convert(
     object[] values, Type targetType, object parameter,CultureInfo culture)
{
    object result = null;

    if (values.Length == 2 && values[0] is string && values[1] is bool)
    {
        var imagePath = (string)values[0];
        var isPublic = (bool)values[1];
        ...
    }

    return result;
}

【讨论】:

  • 那不行 - 它是 Windows Phone - more information
  • 谢谢,您的回答提供了丰富的信息。但是多重绑定对我没有帮助,因为 Windows 手机开发不支持它。对不起,我应该在问题中写清楚。
  • @Fadi 那么你或许应该从你的问题中删除WPF 标签。
猜你喜欢
  • 2015-05-22
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多