2013-02-27 57 views
7

在WPF一个类型,你可以创建一个Style充当默认为XAML控件类型:查找的默认样式在后面的代码

<Style TargetType="{x:Type local:MyControl}"> 
    . . . 
</Style> 

然后,当WPF去显示控制,它根据其类型查找来自资源的Style

我想在我的程序的代码隐藏中做到这一点。我如何找到Style

回答

17

您可以通过使用控制型的关键搜索在应用程序级资源的样式:

Style defaultStyle = Application.Current.TryFindResource(typeof(MyControl)) as Style; 
2

object globalStyleDefinedByApp; 
Style globalStyle = new Style(typeof(TargetType)); 
if (Application.Current.Resources.TryGetValue(typeof(TargetType), out globalStyleDefinedByApp)) 
{ 
    globalStyle = globalStyleDefinedByApp as Style ?? globalStyle; 
} 

如果有人土地在这里寻找一个通用的解决方案Windows项目(UWP),没有TryFindResource存在,所以上面是你如何做到这一点。

相关问题