Noobie3001 Noobie3001 - 1 year ago 221
C# Question

WPF Listview binding - Get bound item in code behind

I'm trying to access the UserControl's bound object (generated from listView itemsource) from codebehind.

I have the following code:

<ListView x:Name="lst1">
<Controls:MyUserControl />

public void Load()
lst1.ItemsSource = List<Customer> from database ......

In each user control that is gererated, I want to access the Customer object that the user control is getting it's values from, ie:

public MyUserControl()

Customer cust = (Customer)this.DataContext;
// cust is null????

This code successfully displays properties from the Customer object, I just can't seem to find it in the code behind.

Please help.

Answer Source

Does the compiler really let you assign object to Customer without a cast?

Anyway, DataContext won't be initialized yet in the constructor.

You could handle the DataContextChanged event, which will be raised whenever DataContext changes -- in this case, that'll probably just be when it's assigned in the course of instantiating the DataTemplate that creates MyUserControl. And that's just what you want.




private Customer _customer;
void MyUserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    _customer = (Customer)DataContext;

Or you could just cast DataContext to Customer whenever you need to use it. Check for null, of course. You didn't say what you're doing with Customer so it's hard to be sure when you would need to do something with it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download