Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access DataContext class instance created in XAML in codebehind?

MyData is a class simply storing a ColorName property.

In XAML I can create an instance for my XAML datacontext by

<c:MyData x:Key="myDataSource">

Now,

How do I access and change the ColorName stored in this instance of MyData (which was created in XAML with "myDataSource" key) in my code behind?

I hope the question is clear. I 'd like to change the color programmatically. How do I get hold of the MyData class instance ? Thank you

<DockPanel
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:SDKSample">
  <DockPanel.Resources>
    <c:MyData x:Key="myDataSource"/>
  </DockPanel.Resources>
  <DockPanel.DataContext>
    <Binding Source="{StaticResource myDataSource}"/>
  </DockPanel.DataContext>
  <Button Background="{Binding Path=ColorName}"
          Width="150" Height="30">I am bound to be RED!</Button>
</DockPanel>
like image 330
iAteABug_And_iLiked_it Avatar asked Jul 05 '13 19:07

iAteABug_And_iLiked_it


1 Answers

To access a resource from code-behind, give the DockPanel a name and then:

var resource = dockPanel.Resources["myDataSource"];

Alternatively, you can get its DataContext:

var dataContext = dockPanel.DataContext as MyData
like image 118
PoweredByOrange Avatar answered Sep 23 '22 16:09

PoweredByOrange