Programmatically accessing data from a datacontext in user user control

I have defined a custom user control that I use in the MVVM Prism Silverlight (C #) application. I use my control this way:

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

Then I would like to use this associated MyDataObject in the code that is inside my DetailTable custom control. I want to first bind the object to the datacontext, as shown, and then in the code behind which these properties of the objects are displayed for labels, text fields, etc. in this user control.

How can this be achieved?

thanks

+4
source share
2 answers

In your code behind, after you set the data context in xaml, you can get the related object using:

 MyDataObjectType dataObject = (MyDataObjectType)detailsTable.DataContext; 

Then you can use dataObject.Property1 as needed.

+2
source

If the text field / text block is in the same view, you can do this by binding the Text property of the text field / 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}/> 
0
source

All Articles