开发者

INotifyPropertyChanged Binding and Cross-Threading Error

开发者 https://www.devze.com 2023-03-22 02:23 出处:网络
I have a GridView element on my GUI that is bound to a data source. I decided to use the INotifyPropertyChanged as that would simplify the interaction by allowing me to modify a class which would auto

I have a GridView element on my GUI that is bound to a data source. I decided to use the INotifyPropertyChanged as that would simplify the interaction by allowing me to modify a class which would automatically update the GridView. Up to this point I have not ha开发者_运维知识库d any problems with cross-threading, but now I added another method that modifies my class (which in turn modifies the GridView), but this is taking place on a non-UI thread. I have solved my problems before by using an invoke, but I am not sure how do to it when I am implementing the INotifyPropertyChanged and binding it to the GridView. Any help would be very much appreciated!


Let's say you have an observable collection that is tied to your grid. The grid is the View.

When a callout is made to retrieve data, the callout will be async to return data. On the Async event handler, you would want something like this in your View Model class:

    /// <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));

    }

Then in SetUsers you would update the observable collection (_Users) that is data bound to the view (grid). Since the observable collection updates, the changes will be reflected in the view since it is bound to the view via a dependency property.

Note, I've omitted the SetUsers() code, but all that is doing is setting the incoming user list to the observable collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消