当其他ObservableCollection更改时,BindableCollection会更改

问题描述 投票:0回答:1

有没有办法用其他ObservableCollection中添加/删除的项更新ObservableCollection?

如何在FullyObservableCollection中添加,删除项目时如何更新我的ViewModel的BindableCollection?

重要的是要注意我正在尝试使用Caliburn.Micro的MVVM模式。

查看模型

private BindableCollection<Employees> _employees = new BindableCollection(OracleConnector.GetEmployeeRepositorys());

public BindableCollection<Employees> Employees
    {
        get
        {

            return _employees;
        }
        set
        {
            OracleConnector.List.CollectionChanged += (sender, args) =>
            {
                _employees = OracleConnector.List;
            };
            NotifyOfPropertyChange(() => Employees);

        }
    }

OracleConnector

public class OracleConnector
{
    public static FullyObservableCollection<Employees> List = new FullyObservableCollection<Employees>();

    public static FullyObservableCollection<Employees> GetEmployeeRepositorys()
    {

        using (IDbConnection cnn = GetDBConnection("localhost", 1521, "ORCL", "hr", "hr"))
        {
            var dyParam = new OracleDynamicParameters();

            try
            {

                var output = cnn.Query<Employees>(OracleDynamicParameters.sqlSelect, param: dyParam).AsList();
                foreach (Employees employees in output)
                {
                    List.Add(employees);
                }

            }
            catch (OracleException ex)
            {
                MessageBox.Show("Connection to database is not available.\n" + ex.Message, "Database not available", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return List;

        }
    }

}

我能够检测是否在FullyObservableCollection中进行了更改,但我不知道如何将它们传递给ViewModel。

wpf observablecollection caliburn.micro
1个回答
0
投票

添加新员工时,请在IEventAggregator类中使用OracleConnector。发布包含新员工的EmployeeAddedMessage。确保您也在正确的帖子上发布。您可能需要使用PublishOnUiThread方法。然后ShellViewModel能够实现IHandle<EmployeeAddedMessage>作为一种可能被称为Handle(EmployeeAddedMessage msg)的方法。在Handle方法中,您可以将Employee添加到相应的Employee集合中。

您可能需要将OracleConnector添加到应用程序引导程序以及Caliburn Micro提供的EventAggregator类。你的ShellViewModel还需要在事件聚合器上调用Subscribe(this)方法。 OracleConnectorShellViewModel都需要使用事件通知程序的相同实例。因此,请确保将事件聚合器注册为单例。

有关使用事件通知的更多详细信息,请参阅here。此外,我的应用程序here使用事件通知来处理应用程序事件。

© www.soinside.com 2019 - 2024. All rights reserved.