【问题标题】:How to set the style in WPF Window.Resources.如何在 WPF Window.Resources 中设置样式。
【发布时间】:2012-02-08 23:26:56
【问题描述】:

我想在 Window.Resources 中创建多个样式。以下是我尝试过的代码,但它不起作用:

<Window.Resources>
    <Style x:Key="StyleOne" TargetType="{x:Type Control}">
        <Setter Property="Control.Background" Value="Blue"></Setter>
        <Setter Property="Control.Height" Value="20"></Setter>
    </Style>
    <Style x:Key="StyleTwo" BasedOn="{StaticResource StyleOne}">
        <Setter Property="Control.Background" Value="Red"></Setter>
        <Setter Property="Control.Height" Value="20"></Setter>
    </Style>
</Window.Resources>
<Button Style="{StaticResource StyleOne}"></Button>
<Button Style="{StaticResource StyleTwo}"></Button>

它抛出一个错误说:

属性“内容”设置了多次。

【问题讨论】:

    标签: wpf xaml resources window styles


    【解决方案1】:

    这个错误与样式无关,窗口只能包含一个孩子(设置Content),使用一些可以包含多个孩子的容器。例如StackPanelGrid

    <StackPanel>
         <Button .../>
         <Button .../>
    </StackPanel>
    

    (另见:Panels Overview

    【讨论】:

    • 我想这不是问题,因为样式元素仅受 window.resource 支持,没有其他元素,我也尝试了 stackpanel 和 grid,问题出在我的第二种样式的 x:Type Control 上,由@Kishore Kumar 解决,无论如何感谢您抽出时间
    【解决方案2】:

    设置第二种样式的目标类型

     <Style x:Key="StyleTwo"
               BasedOn="{StaticResource StyleOne}"
               TargetType="{x:Type Control}">
            <Setter Property="Control.Background"
                    Value="Red"></Setter>
            <Setter Property="Control.Height"
                    Value="20"></Setter>
        </Style>
    

    将按钮放在堆栈面板或网格中

    【讨论】:

      【解决方案3】:

      我猜 BasedOn 继承了其他样式类型的属性,你有

          Property="Control.Background"
      

      同时设置两种样式,因此会出错

          "The property "Content" is set more than once."
      

      【讨论】:

        猜你喜欢
        • 2017-11-29
        • 2019-07-22
        • 1970-01-01
        • 2014-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-26
        • 2014-11-11
        相关资源
        最近更新 更多