【问题标题】:Extend UserControl.Resources扩展 UserControl.Resources
【发布时间】: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


【解决方案1】:

解决方法不足:覆盖默认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 将不再有黑色背景。 (显然我也可以将它添加到最重要的样式中,但在更大范围内这并不实用。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-25
    • 2023-03-27
    • 2019-02-25
    • 2020-09-10
    • 2014-09-23
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多