WPF中的绑定数据未更新

时间:2013-04-02 09:34:29

标签: c# wpf data-binding

我有一个显示一些ListBox的应用程序。这些ListBox绑定到数据。其中一个列表是门列表,而另一个列表是用户列表。

门列表来自与数据库通信的DataManager类。用户列表来自另一个进行一些计算的类。

我已将两个ListBox绑定到它们合适的ObservableList getter setter。

门口:

public ObservableList<Door> Doors
{
    get { return DataManager.Doors; }
}

并为用户:

public ObservableList<User> Users
{
    get { return classLogic._users; }
}

这就是问题所在。当我添加或删除门时,UI上的列表会更新。添加或删除用户时,列表不会更新。我必须重新加载视图(重新启动应用程序)才能更新它。我错过了什么?为什么不起作用?

2 个答案:

答案 0 :(得分:2)

可观察集合为每个项目的属性引发PropertyChanged 就像你有一个IsDoorClosed属性,它会更新

删除元素会在Doors上引发CollectionChanged事件,但UI不会更新 绑定属性门上没有引发PropertyChanged事件。

你需要在每个CollectionChanged门上的Doors上提升一个PropertyChanged事件。

类似于以下内容:这是psado代码,它是作为示例编写的 为了您的利益,请检查是否存在任何语法错误。

 Doors.CollectionChanged += OnDoorsCollectionChanged; 


 private static void OnDoorsCollectionChanged(object sender , CollectionChangedEventArgs e)
 {
      PropertyChanged(sender,new PropertyChangedEventArgs("Doors"));
 }

答案 1 :(得分:1)

我发现自己有三个步骤需要完成。我不相信更新ListBox需要PropertyChanged事件。这可能是因为.NET 4.0,因为我已阅读下面的版本,数据绑定尚不正确。

第一步是列表必须是private static ObservableList<...>。第二个是这个列表的getter也必须是合适的类型。这意味着在我的情况下,以下代码需要在ClassLogic中:

private static readonly ObservableList<User> _users= new ObservableList<User>();

public static ObservableList<User> Users
{
    get { return _users; }
}

第三件事是,在DataContext类中调用此函数(getter)将数据绑定到ListBox时,必须使用类名而不是该类的实例!

所以,在这种情况下,它将是:

/// <summary>
/// Gets the Users that are managed by the ClassLogic class
/// </summary>
public ObservableList<User> Users
{
    get { return ClassLogic.Users; }
    //wrong would be:
    //get { return classLogic.Users }
}

这3个步骤绑定了我的数据,并确保在更新列表内容时更新ListBox。