Access XAML Instantiated Object from C#

c#, oop, wpf, xaml

Solution

Call `FindResource("MyConnection")` (docs). You'll need to cast it to the specific type because resources can be any kind of object.

There is also a TryFindResource method for cases where you're not sure whether the resource will exist or not.

Problem

In my XAML I declare an instance of a class called DataConnection, the instance is named MyConnection. ``` <Window.Resources> <!-- Create an instance of the DataConnection class called MyConnection --> <!-- The TimeTracker bit comes from the xmlns above --> <TimeTracker:DataConnection x:Key="MyConnection" /> <!-- Define the method which is invoked to obtain our data --> <ObjectDataProvider x:Key="Time" ObjectInstance="{StaticResource ResourceKey=MyConnection}" MethodName="GetTimes" /> <ObjectDataProvider x:Key="Clients" ObjectInstance="{StaticResource ResourceKey=MyConnection}" MethodName="GetClients" /> </Window.Resources> ``` Everything in the XAML part works fine. What I want is to be able to reference my instance of MyConnection from my C# code. How is that possible?

Original source