如何访问的ResourceDictionary在WPF从C#code? [英] How can I access ResourceDictionary in wpf from C# code?

查看:1883
本文介绍了如何访问的ResourceDictionary在WPF从C#code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的DataTemplate 中,我想通过C#code访问一个XAML文件中定义。
谁能告诉我怎样才能访问它?
我添加了一个新的 ResourceDictionary中文件,它的名字叫 Dictionary1.xaml
  我有一个数据模板,如:

I have a DataTemplate defined in a xaml file that I want to access via C# code. Can anyone please tell me how can I access it? I added a new ResourceDictionary file and its name is Dictionary1.xaml. I have a data template such as:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DataTemplate x:Key="mytemplate">
        <TextBlock Text="Name:" Background="Blue"/>
    </DataTemplate>
</ResourceDictionary>

不是我有一个的ListBox 名为listBox1中,我想给它的的ItemTemplate 属性分配它
但我没有得到我该怎么办呢?

not I have a ListBox called listBox1 and I want to assign it to it's Itemtemplate property but I'm not getting how can i do it?

推荐答案

正好你在哪里定义呢?

Where exactly are you defining it?

如果在你的对象的定义ResourceDictionary中,然后

If you define it in the ResourceDictionary of your object, then

Application.Current.Resources[typeof(yourDataTemplateTargetType)]

应该工作。如果你把它定义为别的东西一员,像说,一个ItemsControl,你需要得到一个处理ItemsControl的实例,并调用ItemTemplate属性。

should work. If you are defining it as a member of something else, like say, an ItemsControl, you need to get a handle to the ItemsControl instance and call the ItemTemplate property.

编辑:好吧,我想我们取得了一些进展。所以,你要定义在它自己的文件中的ResourceDictionary。之前,你可以在你的UI使用它,并从code后面访问它,你需要到的ResourceDictionary合并到您的应用程序。你在干什么呢?

Ok, I think we're getting somewhere. So you are defining a ResourceDictionary in its own file. Before you can use it in your UI and access it from your code behind, you need to merge that ResourceDictionary into your application. Are you doing this?

如果你是,那么下一步就是要得到这个资源。每个FrameworkElement的有一个名为方法<一href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.findresource.aspx\">FindResource.这种方法是伟大的,因为它走了的ResourceDictionary树,试图找到与关键资源。所以,如果你想从一个用户控件访问这个资源,你可以在code背后的以下内容:

If you are, then the next step is to get this resource. Each FrameworkElement has a method called FindResource. This method is great because it walks up the ResourceDictionary tree and attempts to locate the resource with the key. So, if you want to access this resource from a UserControl, you can do the following in the code behind:

FindResource(typeof(yourDataTemplateTargetType));

如果这不适合你,请告诉我们你究竟是如何声明此资源字典和它是如何得到合并到应用程序的资源。

If this doesn't work for you, please show us exactly how you are declaring this resource dictionary and how it is getting merged into your application's resources.

这篇关于如何访问的ResourceDictionary在WPF从C#code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆