我正在构建一个WPF应用程序,我从标准WPF控件类型派生了一堆控件 - 文本块,按钮等。我尝试将一个资源字典添加到app.xaml来设置主题,但是我的自定义控制似乎不尊重它。 (例如,标准按钮使Aero主题很好,但是从Button派生的myButton仍然是无法看的。)有没有办法可以将派生控件的主题设置为与基本控件相同?
编辑:我应该注意这些自定义控件是在运行时实例化的,所以我无法通过XAML直接操作它们的属性。我可以通过在应用程序资源字典中使用Setter来更改背景颜色等特定属性,但是没有找到使用该技术设置主题的方法。答案 0 :(得分:1)
如果在名为Dictionary1.xaml
的资源字典中有此样式<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="MyButtonStyle"
TargetType="{x:Type Button}"
BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Width" Value="75" />
<Setter Property="Height" Value="23" />
</Style>
</ResourceDictionary>
然后你可以在任何带有此代码的按钮上设置它
Uri resourceLocater = new Uri("/YourAssemblyName;component/Dictionary1.xaml", System.UriKind.Relative);
ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater);
Style myButtonStyle = resourceDictionary["MyButtonStyle"] as Style;
Button button = new Button();
button.Style = myButtonStyle;