Search code examples
c#wpfresourcedictionary

How can I get access to a class backed resource dictionary instance?


I've got a resource dictionary with several control defined in it (TextBox and Button) that are unrelated to each other. I can access the controls via TryFindResource without problems.

Next, I wanted to attach an event to the button, so I added x:Class to the dictionary and created a backing class (based on info I found here) and the event functions correctly.

What I'm having problems with is: how do I gain access to the created resource directory (i.e. my class) that backs the load xaml? Ultimately I want to create a number of complicated controls in the resource directory and have a simple, single function I can call in the backing class to give me the list of those controls back, so I can add them to my window, rather than needing call to TryFindResource for each control.

I have a constructor in the class (and have a call to InitializeComponent), but the auto created internal fields that represent the TextBox and Button are null. The constructor is called early (well before anything in my GUI) but the behind-the-scenese Connect call apparently hasn't been done even by the time my window's Loaded event is called.

I've done a ton of searching but everything I've found stops at the defining the class point and doesn't show any usage after that.

Am I barking up the wrong tree here? I'm sure I'm misunderstanding something about how this all functions and what it's capable of, but it really seems like I should be able to get an instance somehow.

Partial XAML:

<ResourceDictionary x:Class="MM.Window.TitleBarControls"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    <MMM:ApplicationInformation x:Key="ApplicationInformation" />

    <Button x:Key="ButtonTest"
            x:Name="ButtonTest"
            Content="Button"
            Click="ButtonClickTest" />
</ResourceDictionary>

Partial class:

    public partial class TitleBarControls : ResourceDictionary
    {
        public ObservableList<object> HeaderControls = new();

        public TitleBarControls()
        {
            TitleBarControlsMain = this;

            InitializeComponent();

            // ButtonTest is null here
            HeaderControls.Add(ButtonTest);
        }

        private void ButtonClickTest(object sender_, System.Windows.RoutedEventArgs e_)
        {
            int i = 1;
        }
    }

Solution

  • The button in your example is a resource that gets added to the ResourceDictionary itself.

    Remove the x:Name (to avoid confusion) from the XAML markup and access it using the indexer in the code-behind:

    HeaderControls.Add(this["ButtonTest"]);