我在资源字典中为Button控件定义了自定义外观:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Button" x:Key="BaseButtonStyle">
<Setter Property="Background" Value="Blue"/>
</Style>
</ResourceDictionary>然后我试着在按钮所在的窗口中改变样式。
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary.xaml"/>
<ResourceDictionary>
<Style TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="Foreground" Value="Red"/>
</Style>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>在WPF设计器中,我得到了我所期望的。带有红色文本的蓝色按钮。但在运行时,这两种样式都不会应用,并且按钮具有默认颜色。我该如何解决这个问题呢?
发布于 2010-09-23 22:05:53
下面的方法可以正常工作。我只是将样式移出MergedDictionaries,并将其放在外部ResourceDictionary上。
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="Foreground" Value="Red"/>
</Style>
</ResourceDictionary>
</Window.Resources>在你最初的XAML中,我不确定为什么设计器能够正确地呈现它,而WPF运行时却不能。MSDN documentation说:
合并的ResourceDictionary中没有在标记中定义的资源元素。相反,合并后的字典是一个没有定义标记子元素(或者没有通过代码添加元素),但为ResourceDictionary指定了URI的源。
这可能与此有关。
https://stackoverflow.com/questions/3778746
复制相似问题