WPF自定义控件在设计器和运行模式中具有不同的前景

问题描述 投票:1回答:1

在新的WpfApp1中,我添加了一个新的自定义控件(WPF)名称CustomButton。在其静态构造函数中,我将默认前景设置为黄色。在MainWindow.xaml中,我添加了CostomButton。

在设计师中,它的前景是黄色的(正确的)。运行应用程序,前景是黑色(错误)。

任何想法为什么会这样?

CustomButton.cs:

namespace WpfApp1
{
public class CustomButton : Button
{
    static CustomButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));

        CustomButton.ForegroundProperty.OverrideMetadata(typeof(CustomButton),
            new FrameworkPropertyMetadata(Brushes.Yellow));
    }
}

Generic.xaml:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1">

<Style TargetType="{x:Type local:CustomButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomButton}">
                <Button
                    Foreground="{TemplateBinding Foreground}"
                    Content="asdf 01">
                </Button>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

MainWindow.xaml:

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <local:CustomButton Width="200" Height="100"/>
</Grid>

c# wpf custom-controls
1个回答
0
投票

自定义Button的默认前景似乎被应用程序范围的样式覆盖。

而不是更改默认前景,将Setter添加到控件的默认样式:

<Style TargetType="local:CustomButton">
    <Setter Property="Foreground" Value="Yellow"/>
    ...
</Style>
© www.soinside.com 2019 - 2024. All rights reserved.