更新从另一个列表接收项目的 ObservableCollection

Update ObservableCollection where the items are received from another List

我想在 ItemsControl 中动态显示我所有的联系人。 我的逻辑中有一个联系人列表(如果有人删除了我或者有人接受了我的请求,这个列表就会更新)并且我已经将这个列表添加到绑定到 ListBox 的 ObservableCollection<>。

C#

Contacts = new ObservableCollection<Contact>(MyLogic.Current.Contacts);

XAML

<ItemsControl ItemsSource="{Binding Contacts}" x:Name="MainPanel">

问题来了: 当我想将联系人添加到我的联系人列表时,ObservableCollection 没有更新

MyLogic.Current.Contacts.Add(new Contact("Fred", true));

ObservableCollection 不适用于来源 List。当您从现有 List 创建它时,它只会将元素从它复制到内部存储。 因此,您应该将元素添加到 ObservableCollection 本身以获得您想要的等等。

您遇到的问题是您希望 ObservableCollection 在您添加到 List 时自动更新。这不是真的。

当您实例化您的 ObservableCollection 时,您正在获取 List副本,而不是对列表本身的引用。

因此,当您添加新项目时,您应该添加到您的 ObservableCollection,而不是您的 List。或两者。但我不明白为什么你需要两者,我建议完全放弃你的 List

这不是最佳解决方案,但如果您想查看问题出在哪里,以下代码会更新您的 UI:

var newContact = new Contact("Fred", true));
MyLogic.Current.Contacts.Add(newContact);
Contacts.Add(newContact);

更好的解决方案是 MyLogic.Current.Contacts 更改通过事件通知您 UI。

编辑:

The problem is that I can only update the LIST and not the ObservableCollection(the list itself is in a different project)... so I need a way to update the GUI when that LIST is updated

要在您的数据更改时通知 UI,您可以使用以下事件:

首先定义一个 EventArgs 来显示新添加的项目,如下所示:

public class ModelAddedEventArgs<TModel> : EventArgs
{
    public ModelAddedEventArgs(TModel newModel)
    {
        NewModel = newModel;
    }

    public TModel NewModel { get; set; }
}

然后在您的 MyLogic 类中定义一个 EventHandler,如下所示:

public event EventHandler<ModelAddedEventArgs<Contact>> ContactAdded;

    public void AddModel(Contact model)
    {
        // first add your contact then:
        if (ActivityGroupAdded != null)
            ActivityGroupAdded(this, new ModelAddedEventArgs<Contact>(model));
    }

最后用你的EventHandler通知UI:

    private void YourUIConstructor()
    {
        MyLogic += OnContactAdded;
    }
    private void OnContactAdded(object sender, ModelAddedEventArgs<Contact> e)
    {
        Contacts.Add(e.NewModel);
    }