WPF数据绑定到更改对象 [英] WPF Data Binding to changing object

查看:152
本文介绍了WPF数据绑定到更改对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这显示当前登录的用户名的用户控件。我已经在控制用户obejct在我的应用程序的用户ID属性绑定一个TextBlock。

I have a user control which displays the currently logged in user's name. I have bound a TextBlock in the control to the UserId property of a User obejct in my application.

我的问题是,用户对象我绑定有作为源每一次改变了一个新用户登录。

The issue I have is that the User object my binding has as a source changes each time a new user logs in.

我能想到的地方我火的事件当用户obejct变化,这是我所控制,然后重新初始化是抓住了解决方案的结合,但是这似乎不太理想。

I can think of a solution where I fire an event when the User obejct changes and this is caught my by control which then reinitialise's the binding but this seems less than ideal.

是否有这个问题的解决方案,我觉得那一定是很常见的?

Are there a solution to this issue, I feel it must be very common?

干杯,

詹姆斯

推荐答案

大多数UI绑定已经通过物业通知,特别是(对WPF)处理这个 INotifyPropertyChanged的。 - 也就是说,如果你在更新一个用户ID的的实例:

Most UI bindings already handle this via property notifications, in particular (for WPF) INotifyPropertyChanged. - i.e. if you are updating the UserId on a single instance:

class User : INotifyPropertyChanged {
   public event PropertyChangedEventHandler PropertyChanged;
   protected virtual void OnPropertyChanged(string propertyName) {
      PropertyChangedEventHandler handler = PropertyChanged;
      if(handler!=null) handler(this, new PropertyChangdEventArgs(
                                            propertyName));
   }
   private string userId;
   public string UserId {
       get {return userId;}
       set {
           if(userId != value) {
              userId = value;
              OnPropertyChanged("UserId");
           }
       }
   }
}

这应该然后自动更新绑定。如果你是,相反,改变实际用户实例,然后再考虑同样的伎俩,而是反对任何托管用户:

This should then update the binding automatically. If you are, instead, changing the actual user instance, then consider the same trick, but against whatever hosts the user:

public User User {
    get {return user;}
    set {
        if(user != value) {
            user = value;
            OnPropertyChanged("User");
        }
    }
}

如果你绑定的东西的User.UserId,那么它​​应该工作。

And if you are binding to something's "User.UserId", then it should work.

这篇关于WPF数据绑定到更改对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆