我可以应用“StaticResource”吗?到运行时的元素?
我可以在运行时将“StaticResource”应用于元素吗?
我知道我可以使用“StaticResource”作为 xaml 文件中的元素。但是,我想知道如何从 C#(代码隐藏)中使用它。
Can I apply "StaticResource" to element in run-time?
I know I can use "StaticResource" to element in xaml files. But, I want to know how to use it from C# (code-behind).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
StaticResource
是静态定义的资源,通常在任何元素或页面的
元素中定义。在 C# 中,您只需使用
X.Resources["MyResource"]
访问它,就像{StaticResource MyResource}
那样。A
StaticResource
is a static defined resource, usually defined in the<X.Resources>
element, for any element or page.In C# you simply access it with
X.Resources["MyResource"]
like you should do{StaticResource MyResource}
.其实并不是同一个意思。
StaticResources
是“静态”的,因为它们的值是在 Xaml 解析期间解析的。 XamlParser 将通过检查资源字典、同一个 xaml 中的祖先FrameworkElement
Resource
属性以及 Application.Resources 来解析资源。如果需要的话。如果您碰巧知道在哪里可以使用 C# 代码找到要分配的资源,那么就像 Claus 的回答一样简单。但是,如果您只知道资源的名称,而不知道它在哪个字典中找到,那么这就更麻烦了。
可以编写一个例程(您可能可以在 SO 或网络上的其他地方找到一个例程),您可以使用该例程使用
VisualTreeHelper
查看所有Resource< /code> 沿途的属性。您可能可以摆脱这种情况,但请注意,这可能会比原始 Xaml 版本搜索更多的字典,并且您可能会获得一些意想不到的值。
Not really with the same meaning.
StaticResources
are "static" in the sense that their value is resolved during Xaml parsing. The XamlParser will resolve the resource by examining the resource dictionary the ancestorFrameworkElement
Resource
properties that are also in the same xaml and then the Application.Resources if necessary.If you happen to know where to find the resource you want to assign using C# code then it is as simple as in Claus' answer. However if you only know the name of the resource but not which dictionary its found in then its much tricker.
It is possible to write a routine (you can probably find one in SO or elsewhere on the web) that you can use to hunt up the Visual tree using the
VisualTreeHelper
looking at all theResource
properties along way. You could probably get away with this but be aware that this may search more dictionaries than the original Xaml version would and its possible for you to get some unexpected value.