I am figuring out binding in WPF, and running into an issue with object binding.
I have a combobox with an itemsource set to a list of Users
ICollection<User> users = User.GetAll();
cmbContacts.ItemsSource = users;
I also have an object in my UI which holds the selected user.
public partial class MainWindow : Window
{
private User selectedUser = new User();
public MainWindow()
{
InitializeComponent();
ReloadContents();
Binding b = new Binding();
b.Source = selectedUser;
b.Path = new PropertyPath("uFirstName");
this.txtFirstName.SetBinding(TextBox.TextProperty, b);
}
And in my combobox’s SelectChanged method…
selectedUser = (User)e.AddedItems[0];
However, the textbox is not updating! I can verify that my binding works by moving the binding code to the combobox SelectChanged methods
selectedUser = (User)e.AddedItems[0];
Binding b = new Binding();
b.Source = selectedUser;
b.Path = new PropertyPath("uFirstName");
this.txtFirstName.SetBinding(TextBox.TextProperty, b);
Now the textbox updates fine. This seems like the incorrect way of doing things. Can anyone point me in the right direction?
In your code I see one bug – when you set field selectedUser you don’t notify that this data has been changed. Your sample should looks like this:
And don’t forget that now you will need to set new value to the property, don’t use field, so the SelectChanged should looks like: