Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing DataContext to User Control in WPF

I have a usercontrol that acts as a container for a ContentControl.
The user control container has a listview control that I want to use to update controls in a dynamically added user control assigned to the ContentControl.
IOW, as I scroll through the listview control, the textbox's in the UC assigned to the ContentControl should update.

I've done this when everything is in one page no problem, but am having a hard time passing the ListView as a datacontext to the dynamically added UC.

How can this be done?

In XAML

 <ListView x:name="lstIncidents">

 </Listview>

 <ContentControl x:Name="PlaceHolder"></ContentControl>

In Codebehind...

PlaceHolder.Content = new LocationView();

When adding the "LocationView" to the PlaceHolder.Content, I need to pass "lstIncidents" as the datacontext so the textboxs in "LocationView" refresh as the ListView is navigated.

like image 207
AshbyEngineer Avatar asked Jul 18 '09 02:07

AshbyEngineer


1 Answers

Controls inherit their DataContext from their parent, so try setting the DataContext on the ContentControl:

<ContentControl 
    x:Name="PlaceHolder"
    DataContext="{Binding SelectedItem,ElementName=lstIncidents}" />
like image 103
Matt Hamilton Avatar answered Sep 19 '22 20:09

Matt Hamilton