Aljaz Vidmar
Aljaz Vidmar

Reputation: 675

Programmatically access data from datacontext in custom user control

I have defined a custom user control which I use in a MVVM Prism Silverlight (c#) application. I use my control in a view like this:

<my2:DetailsTable Name="detailTable" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Stretch" 
                HorizontalContentAlignment="Stretch" 
                VerticalContentAlignment="Stretch"
                DataContext="{Binding MyDataObject}" />

Then I would like to use this bound MyDataObject in code behind inside my custom control DetailTable. I want to first bind the object to datacontext as shown and then in code behind display this objects properties to labels, textboxes, etc. in this custom user control.

How can achieve this?

Upvotes: 4

Views: 2149

Answers (2)

Mostlyharmless
Mostlyharmless

Reputation: 2283

In your code behind, after you have set the data context in the xaml, you can retrieve the bound object using:

MyDataObjectType dataObject = (MyDataObjectType)detailsTable.DataContext;

Then you can use dataObject.Property1 as needed.

Upvotes: 3

Pradeep
Pradeep

Reputation: 484

If the textbox/textblock in the same view then you can do this by binding Text property of the text box / text block with MyDataObject.Property1 etc.

Sample code.

<my2:DetailsTable Name="detailTable"
       HorizontalAlignment="Stretch" 
       VerticalAlignment="Stretch"  
       HorizontalContentAlignment="Stretch"
       VerticalContentAlignment="Stretch"                 
       DataContext="{Binding MyDataObject}" />
<TextBox Text={Binding MyDataObject.Property1}/>
<TextBlock Text={Binding MyDataObject.Property2}/>

Upvotes: 0

Related Questions