Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access XAML Instantiated Object from C#

Tags:

c#

oop

wpf

xaml

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?

like image 508
Ryan Avatar asked Jan 11 '10 01:01

Ryan


2 Answers

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.

like image 192
itowlson Avatar answered Oct 18 '22 12:10

itowlson


FindResource will search the element's resource dictionary as well as any parent elements' resource dictionaries and the application resources.

Resources["MyConnection"] will search only the resource dictionary of that element.

void Window_Loaded(object sender, RoutedEventArgs args) {
    DataConnection dc1 = this.FindResource("MyConnection") as DataConnection;
    DataConnection dc2 = this.Resources["MyConnection"] as DataConnection;
}

The documentation recommends the first approach for normal resource lookups but provides the second approach for when you are retrieving resources from a "known resource dictionary location ... to avoid the possible performance and scope implications of run-time key lookup." link

like image 5
Josh Avatar answered Oct 18 '22 12:10

Josh