Access to XAML object with C #

In my XAML, I declare an instance of the DataConnection class, 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. I want to be able to reference my MyConnection instance from my C # code.

How is this possible?

+5
source share
2 answers

Call FindResource("MyConnection")( docs ). You will need to specify it for a specific type, because resources can be any objects.

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

+5
source

FindResource , .

Resources [ "MyConnection" ] .

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

, , " ..., ".

+5

All Articles