8

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>
iAteABug_And_iLiked_it
  • 3,725
  • 9
  • 36
  • 75

1 Answers1

17

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
Arian Motamedi
  • 7,123
  • 10
  • 42
  • 82
  • 3
    Your 'Alternative' is Superlative – Scott Solmer Aug 18 '16 at 14:31
  • I'm doing something similar: I say the following in the event handler of the button that is trying to read the text from textBox ```var dataContext = myWindow.DataContext as myClass;``` and then using it as ```System.Windows.MessageBox.Show(dataContext.Text);```, but ```dataContext``` stays null. What might be the problem? – miguello Jun 22 '22 at 18:31