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.
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?
Cheers,
James
The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .
Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.
Binding path syntax. Use the Path property to specify the source value you want to bind to: In the simplest case, the Path property value is the name of the property of the source object to use for the binding, such as Path=PropertyName . Subproperties of a property can be specified by a similar syntax as in C#.
The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from.
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");
}
}
}
And if you are binding to something's "User.UserId", then it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With