如何从资源字典继承/扩展样式?
我在扩展我在 Windows 字典中定义的样式之一时遇到问题。单独来看,它似乎按预期将样式应用于我的控件。但是,如果尝试使用 basedOn 属性扩展我的用户控件之一中的样式,它只会覆盖主样式,并且所有基本样式都会消失。下面是一个示例:
在名为 dict1.xaml 的资源字典中:
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Pink"/>
</Style>
在主 window.xaml 中:
<Window.Resources>
<ResourceDictionary Source="dict1.xaml"/>
</Window.Resources>
在名为 userControl1.xaml 的用户控件中:
<UserControl.Resources>
<Style BasedOn="{StaticResource {x:Type Button}}"
TargetType="{x:Type Button}">
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</UserControl.Resources>
用户控件中的样式仅覆盖资源字典中的样式,并且字体为粗体。如果我删除用户控件中的样式,字典中的样式就会生效,背景会变成粉红色。我两个都想要。
I am having trouble extending one of my styles that I have defined in the Windows dictionary. Alone, it seems to apply the style to my controls as expected. However, if try to extend the style in one of my userControls, using the basedOn property, it simply overrides the main one and all the base styles dissapear. Here's an example:
In a resource dictionary, named dict1.xaml:
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Pink"/>
</Style>
In the main window.xaml:
<Window.Resources>
<ResourceDictionary Source="dict1.xaml"/>
</Window.Resources>
In a user control called userControl1.xaml:
<UserControl.Resources>
<Style BasedOn="{StaticResource {x:Type Button}}"
TargetType="{x:Type Button}">
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</UserControl.Resources>
The style in the user control simply overrides the one in the resource dictionary and the font is Bold. If I remove the style in the user control, the style in the dictionary kicks in and the background becomes pink. I want both.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将字典添加到 UserControl 资源,或者将其添加到 App.XAML 资源。
事实上,UserControl 无法解析该 StaticResource——它位于 UserControl 的范围内,而不是窗口的范围内,如果这有意义的话。
You either need to add the dictionary to the UserControl resources, or add it to App.XAML resources.
As it is, the UserControl can't resolve that StaticResource -- it is in the scope of the UserControl, not the window, if that makes sense.