INotifyPropertyChanged绑定和交叉线程错误

时间:2011-07-22 16:00:04

标签: c# user-interface multithreading

我的GUI上有一个绑定到数据源的GridView元素。我决定使用INotifyPropertyChanged,这样可以简化交互,允许我修改一个自动更新GridView.的类。到目前为止,我没有遇到任何跨线程问题,但现在我添加了另一个修改我的类的方法(它反过来修改了GridView),但这是在非UI线程上进行的。我之前使用invoke解决了我的问题,但是当我实现INotifyPropertyChanged并将其绑定到GridView时,我不确定该怎么做。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

假设您有一个与您的网格绑定的可观察集合。网格是视图。

当进行标注以检索数据时,标注将是异步以返回数据。在Async事件处理程序中,您需要在View Model类中使用类似的东西:

    /// <summary>
    /// This is what is bound to the UI
    /// </summary>
    private ObservableCollection<UserDTO> _Users;

    /// <summary>
    /// Collection of Users
    /// </summary>
    public ObservableCollection<UserDTO> Users
    {
        get
        {
            return _Users;
        }
        set
        {
            if (_Users != value)
            {
                _Users = value;
                OnPropertyChanged("Users");
            }
        }
    }

    /// <summary>
    /// Asynchronous Callback For Get Users
    /// </summary>
    private void UserAgentGetCompleted(object sender, List<UserDto> users)
    {

         //Make sure we are on the UI thread
          this.Dispatcher.BeginInvoke(() => SetUsers(users));

    }

然后在SetUsers中,您将更新作为绑定到视图(网格)的数据的可观察集合(_Users)。由于可观察集合更新,因此更改将反映在视图中,因为它通过依赖项属性绑定到视图。

注意,我省略了SetUsers()代码,但所做的只是将传入用户列表设置为可观察集合。