【问题标题】:wpf listview item updated, property event handler is nullwpf listview 项目已更新,属性事件处理程序为空
【发布时间】:2014-01-08 18:35:25
【问题描述】:

我有一个 WPF ListView,我在其中添加了具有字符串和图像的对象。图像应该是类似星星的东西,根据对象的其他内容有条件地显示它。在我的 XAML 中,我将它绑定到一个名为“Brand”的属性,该属性返回一个 BitmapImage。如果我总是尝试显示图像,一切正常。如果我尝试有条件地显示图像(通过一些 C#),我无法更新 ListView。

我尝试将 INotifyPropertyChanged 添加到添加到 ListView 的对象中,这样我就可以在我希望图像出现时手动触发事件。问题是事件始终为空。就像 ListView 没有订阅它一样。

    <ListView Name="MyListView" Grid.Row="3" SelectionMode="Multiple">
        <ListView.View>
            <GridView>                    
                <GridViewColumn Header="Brand">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Brand}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>

以下 2 行是我将对象添加到 ListView 的方式。数据是从文件中读出的,我省略了一些变量设置。

LineItem li = new LineItem();
MyListView.Items.Add( li );

这是类减去其他属性后的样子。

public class LineItem : IComparable, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public bool PersistedBrand { get { return m_brand; } 
        set { 
            m_brand = value;
            Brand = null;
            //PropertyChanged(this, new PropertyChangedEventArgs("Brand")); 
        } }

    public BitmapImage Brand
    {
        get
        {
            if (ShowBrand)
            {
                return s_brandImage;
            }
            else
            {
                return null;
            }
        }
        set
        {
            PropertyChanged(this, new PropertyChangedEventArgs("Brand")); 
             // EXCEPTION HERE ABOVE!
        }
    }
}

我在这里对绑定应该如何工作的理解有误吗?任何建议表示赞赏。

mj

编辑 1 我添加了更多代码。

【问题讨论】:

  • 这不能回答您的问题,但您应该始终首先检查事件处理程序是否为空(根据 Johan 的回答)。
  • 我认为我们需要看到更多的视图模型类和/或更多的 XAML。
  • 我更新了代码。这真的很简单。没有其他值得注意的 XAML 更改,因为它们仅与屏幕上的其他项目相关。

标签: c# wpf binding


【解决方案1】:

在调用之前检查处理程序是否为空:

public BitmapImage Brand
{
    get
    {
        // ...
    }
    set
    {
        if (Equals(value, _brand)) return;
        _brand = value;
        OnPropertyChanged();
    }
}

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

【讨论】:

  • 是的,我知道那个。但为什么它是空的?
  • 没有订阅时为空。
  • 我认为 OP 试图问为什么没有订阅者。
  • 例如,如果您在视图模型绑定到视图之前设置属性。
  • 是的,可能是事情发生的顺序。我认为在 nullcheck 之后提出事件可能会解决问题。
猜你喜欢
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2010-11-27
  • 1970-01-01
  • 2020-06-19
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多