tags:

views:

260

answers:

2

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?

+1  A: 

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.

itowlson
+1  A: 

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

Josh Einstein