【发布时间】:2012-10-13 23:13:25
【问题描述】:
我想为UserControl 提供一个简单的默认样式,但在使用控件时仍然能够扩展或覆盖该样式。下面是一个示例场景,其中包含一个简单的UserControl 和一个包含控件的Window。目的是让Window 中提供的Button 的样式覆盖UserControl 中定义的默认样式。
用户控制
<UserControl x:Class="Sample.TestControl" ... >
<UserControl.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Margin" Value="2" />
<Setter Property="Foreground" Value="Orange" />
</Style>
<Style TargetType="{x:Type StackPanel}">
<Setter Property="Background" Value="Black" />
</Style>
</UserControl.Resources>
<StackPanel>
<Button Content="Press Me" />
<Button Content="Touch Me" />
<Button Content="Tap Me" />
</StackPanel>
</UserControl>
窗口
<Window x:Class="Sample.MainWindow" ... >
<Grid>
<local:TestControl>
<local:TestControl.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Margin" Value="2" />
<Setter Property="Foreground" Value="Green" />
</Style>
</local:TestControl.Resources>
</local:TestControl>
</Grid>
</Window>
问题
上面的代码会导致:
- 异常:
Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception. - 内部异常:
Item has already been added.
上面的代码试图将两个具有相同键的样式提交到同一个ResourceDictionary,所以显然它不起作用。我猜我无法为按钮提供默认样式...
【问题讨论】:
-
我知道合并后的字典可以有多个资源同一个key,最后一个优先。有什么方法可以使用它吗?
标签: wpf wpf-controls resourcedictionary