简体   繁体   English

从C#访问XAML实例化对象

[英]Access XAML Instantiated Object from C#

In my XAML I declare an instance of a class called DataConnection, the instance is named MyConnection. 在我的XAML中,我声明了一个名为DataConnection的类的实例,该实例名为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. XAML部分中的所有内容都可以正常工作。 What I want is to be able to reference my instance of MyConnection from my C# code. 我想要的是能够从我的C#代码引用我的MyConnection实例。

How is that possible? 怎么可能?

Call FindResource("MyConnection") ( docs ). 调用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. 对于您不确定资源是否存在的情况,还有一个TryFindResource方法。

FindResource will search the element's resource dictionary as well as any parent elements' resource dictionaries and the application resources. FindResource将搜索元素的资源字典以及任何父元素的资源字典和应用程序资源。

Resources ["MyConnection"] will search only the resource dictionary of that element. 资源 [“MyConnection”]将仅搜索该元素的资源字典。

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 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM