I’ve built an interface formed by a ListView and a panel with a few textboxes. In order to make change the context in those textboxes when another ListViewItem is selected, I’ve captured the SelectionChange event, to change accordingly DataContexts of the textboxes. Something like this:
void customersList_SelectItem(object sender, SelectionChangedEventArgs e)
{
Customer customer = (Customer)customersList.Selected;
if (customer != null)
{
addressField.DataContext = customer;
phoneField.DataContext = customer;
mobileField.DataContext = customer;
webField.DataContext = customer;
emailField.DataContext = customer;
faxField.DataContext = customer;
...
}
}
Now, I wonder, is this the best the way to do it? Looks like a bit forced, but I can’t devise any better.
If the textboxes were all contained in a containing element (e.g. a Grid), then you could just set the DataContext of the Grid element instead. This would be cleaner.
Even better yet would be to use XAML binding and MVVM, and this code could be implemented declaratively in XAML.