我希望为UserControl提供一个简单的默认样式,但在使用该控件时仍然能够扩展或覆盖该样式。下面是一个包含控件的简单UserControl和Window的示例场景。其意图是让Window中提供的Window样式覆盖UserControl中定义的默认样式。
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中,因此很明显这是行不通的。我猜我不能为按钮提供默认的样式.
发布于 2012-10-13 23:14:29
不足解决方案:覆盖默认ResourceDictionary
<Window x:Class="Sample.MainWindow" ... >
<Grid>
<local:TestControl>
<local:TestControl.Resources>
<ResourceDictionary>
<Style TargetType="{x:Type Button}">
<Setter Property="Margin" Value="2" />
<Setter Property="Foreground" Value="Green" />
</Style>
</ResourceDictionary>
</local:TestControl.Resources>
</local:TestControl>
</Grid>
</Window>通过将自定义Button样式放入ResouceDictionary中,我可以覆盖默认样式。但是,它不仅覆盖了Button样式,而且覆盖了所有资源。因此,StackPanel将不再有黑色背景。(显然,我也可以将这一点添加到压倒一切的风格中,但这在更大的范围内是不现实的。)
https://stackoverflow.com/questions/12877845
复制相似问题