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">
<ListView.ItemTemplate>
<Controls:MyUserControl />
</ListView.ItemTemplate>
<ListView>
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()
{
InitializeComponent();
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.
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.
XAML
<UserControl
...
DataContextChanged="MyUserControl_DataContextChanged"
...
C#
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.