我正在构建一个 WPF应用程序,我从标准 WPF控件类型派生了一堆控件 – 文本块,按钮等.我尝试将一个资源字典添加到app.xaml来设置主题,但我的自定义控件不是似乎很尊重它. (例如,标准按
编辑:我应该注意这些自定义控件在运行时实例化,所以我无法通过XAML直接操作它们的属性.我可以通过在应用程序资源字典中使用Setter来更改背景颜色等特定属性,但是没有找到使用该技术设置主题的方法.
如果在名为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;