3

I have a windowless application that only consists of an App.xaml which is filled by a ResourceDictionary. How can I access a control in that Dictionary from its codebehind?

Lennart
  • 9,657
  • 16
  • 68
  • 84

1 Answers1

3

After trying various methods that all didn't work, such as getting the control via VisualTreeHelper, accessing the control directly via name, the solution is surprisingly simple:

ResourceDictionary.xaml

<ResourceDictionary x:Class="My.Namespace"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Button x:Key="myButtonName" />

</ResourceDictionary>

ResourceDictionary.xaml.cs:

// Example with a button control
Button myButton= this["myButtonName"] as Button;

if(myButton != null)
{
 // Do something
}
Lennart
  • 9,657
  • 16
  • 68
  • 84