wpf 在后面的代码中查找类型的默认样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15123714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the default style for a type in code behind
提问by Tony Vitabile
In WPF, you can create a Stylethat acts as the default for a control type in XAML:
在 WPF 中,您可以创建一个Style作为 XAML 中控件类型的默认值:
<Style TargetType="{x:Type local:MyControl}">
. . .
</Style>
Then, when WPF goes to display that control, it looks up that Stylefrom the resources based on the its type.
然后,当 WPF 显示该控件时,它会Style根据其类型从资源中查找该控件。
I want to do the equivalent of this in the code-behind of my program. How do I find that Style?
我想在我的程序的代码隐藏中做同样的事情。我怎么找到那个Style?
回答by ZF.
You can search for the style in the Application-level resources by using the control type as the key:
您可以在应用层资源中以控件类型为关键字搜索样式:
Style defaultStyle = Application.Current.TryFindResource(typeof(MyControl)) as Style;
回答by bc3tech
object globalStyleDefinedByApp;
Style globalStyle = new Style(typeof(TargetType));
if (Application.Current.Resources.TryGetValue(typeof(TargetType), out globalStyleDefinedByApp))
{
globalStyle = globalStyleDefinedByApp as Style ?? globalStyle;
}
In case somebody lands here looking for a solution for Universal Windows Projects (UWP), no TryFindResourceexists so the above is how you have to do it.
如果有人来到这里寻找通用 Windows 项目 (UWP) 的解决方案,则不TryFindResource存在,因此以上是您必须执行的操作。

