【问题标题】:WPF ResourceDictionary and BindingWPF 资源字典和绑定
【发布时间】:2023-04-01 11:31:01
【问题描述】:

我是 WPF 的初学者。我想做和 css/sass 一样的东西。我想重用一些定义。

在这里,我想在元素(例如按钮)中重用颜色定义。如果我使用“staticresource”绑定,运行时会出现以下异常:

“PresentationFramework.dll 中出现“System.Windows.Markup.XamlParseException”类型的未处理异常 附加信息:"#FF8FA2AC" ist kein gültiger Wert für die Eigenschaft "Background"。"

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    >

    <Color x:Key="cyan3">#007ca9</Color>
    <Color x:Key="mangenta2">#a8005c</Color>
    <Color x:Key="wintergrey1">#e6ecf0</Color>
    <Color x:Key="wintergrey2">#c3ced5</Color>
    <Color x:Key="wintergrey3">#8fa2ac</Color>
    <Color x:Key="wintergrey4">#506671</Color>
    <Color x:Key="white">#FFFFFF</Color>
    <Color x:Key="antrazit">#333333</Color>

    <!-- Base style for button -->
    <Style TargetType="Button" x:Key="btnStandard">
        <!--Setter Property="Background" Value="#8fa2ac"/-->
        <Setter Property="Background" Value="{StaticResource wintergrey3}"/>
        <Setter Property="Foreground" Value="#ffffff"/>
        <Setter Property="Width" Value="150" />
        <Setter Property="Height" Value="30"/>
    </Style>
</ResourceDictionary>

如何在其他元素中使用预定义定义?或者有什么问题。我想定义 4 种不同的按钮样式“Standard”、“IsFocused”、“IsDisabled”和“IsHero (background=mangenta2”。

【问题讨论】:

  • Background 不是颜色,而是Brush。在资源中声明画笔(例如 SolidColorBrush)并在您的样式和视图中重用它们;顺便说一句,&lt;Setter Property="Background" Value="#8fa2ac"&gt; 从“#8fa2ac”十六进制代码创建一个画笔
  • 我已将&lt;Color x:Key="cyan3"&gt;#007ca9&lt;/Color&gt; 更改为&lt;SolidColorBrush x:Key="cyan3"&gt;#007ca9&lt;/SolidColorBrush&gt;

标签: css wpf resourcedictionary


【解决方案1】:

您应该将 Background 属性设置为 Brush。如果您将其设置为 SolidColorBrush,您可以将它的 Color 属性设置为您的 Color 资源,如下所示:

<Style TargetType="Button" x:Key="btnStandard">
    <Setter Property="Background">
        <Setter.Value>
            <SolidColorBrush Color="{StaticResource wintergrey3}" />
        </Setter.Value>
    </Setter>
    <Setter Property="Foreground" Value="#ffffff"/>
    <Setter Property="Width" Value="150" />
    <Setter Property="Height" Value="30"/>
</Style>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    相关资源
    最近更新 更多