开发者

Programmatically access data from datacontext in custom user control

开发者 https://www.devze.com 2023-03-19 00:52 出处:网络
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:

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?


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.


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}/>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号