Lennart
Lennart

Reputation: 10343

How do I access a control in a Resource Dictionary from its code behind?

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?

Upvotes: 3

Views: 1598

Answers (1)

Lennart
Lennart

Reputation: 10343

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
}

Upvotes: 3

Related Questions