代码之家  ›  专栏  ›  技术社区  ›  el-nino

WPF按钮样式模板已启用

  •  1
  • el-nino  · 技术社区  · 11 年前

    我的申请基于此 example

    我需要自己的按钮样式(没有鼠标悬停动画等),所以我在app.xaml中创建了这个样式:

    <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="SnapsToDevicePixels" Value="true"/>
            <Setter Property="OverridesDefaultStyle" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border x:Name="Border"
                            CornerRadius="2" BorderThickness="1"
                            Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}">
                            <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" />
                                <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBorderBrush}" />
                                <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    

    我的按钮: <Button IsEnabled="true"/>

    现在如果我把按钮改成 <Button IsEnabled="false"/> 我的应用程序在开始时崩溃,出现如下错误:“{DependencyProperty.UnsetValue}”不是属性“BorderBrush”的有效值。

    我做错了什么?

    1 回复  |  直到 11 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    这与静态引用有关。

    特别是,XAML解析在顺序上非常敏感-您必须确保 x:Key="DisabledForegroundBrush" 被引用 之前 解析器以上面的样式到达该行-即使上面的样式与 DisabledForegroundBrush .

    如果你还没有刷子 禁用的前景笔刷 ,如果不需要,可以删除上面代码中引用它的行,或者如果需要,可以按如下方式创建一行:

    <SolidColorBrush x:Key="DisabledForegroundBrush" Color="Red" />
    

    您可以根据需要选择颜色。或者,您可以在此处选择其他类型的笔刷: http://msdn.microsoft.com/en-us/library/aa970904(v=vs.110).aspx

    如果你已经有了一个你想使用的画笔,那么如果你能提供一些关于画笔在代码库中的位置(例如它在资源字典中吗?)以及 禁用的前景笔刷 画笔是,这可能会帮助我找到一个实际的解决方案/确保画笔被引用的最佳方式。

    注意:如果您无法确保 禁用的前景笔刷 首先解析的是更改 StaticResource DynamicResource ,但不建议这样做,除非资源的链接在运行时可能会发生更改(请参见 What's the difference between StaticResource and DynamicResource in WPF? )

    更简单的解决方案:

    如果您只想在中硬编码样式,而不是在外部引用前景笔刷,则可以更改行:

    <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/>
    

    至:

    <Setter Property="Foreground" Value="[SOME COLOR]"/>
    

    不需要为字体创建单独的画笔对象。