为什么样式没有从代码中应用?

Why is the Style not getting applied from code?

我正在尝试从代码创建一个按钮并更改悬停颜色,但由于某些原因,设置器等没有得到应用。我很确定我要么错过了一步,要么是别的什么,但没有任何变化,甚至没有悬停时的颜色。我不是想在 XAML 中创建按钮,而是在代码中创建它,我知道如何在 XAML 中创建它。

System.Windows.Controls.Button createPlaylist = new System.Windows.Controls.Button()
     {
        Height = 100,
        Width = 100,
        Margin = new Thickness(0,50,0,0)
    };

    //                                      STYLE END                                   //
    var dt = new DataTemplate();

    Style style = new Style(typeof(System.Windows.Controls.Button), createPlaylist.Style);

    Trigger t = new Trigger();
    t.Property = IsMouseOverProperty;
    t.Value = true;
    Setter setter = new Setter();
    setter.Property = BackgroundProperty;
    setter.Value = Brushes.Blue;
    t.Setters.Add(setter);

    Trigger s = new Trigger();
    s.Property = IsMouseOverProperty;
    s.Value = false;
    Setter set = new Setter();
    set.Property = BackgroundProperty;
    set.Value = Brushes.Red;
    s.Setters.Add(setter);

    style.Triggers.Add(t);

    createPlaylist.Style = style;

您必须在按钮模板中管理边框的背景颜色,而不是仅仅更改按钮本身的背景 属性。

即做相当于这个 XAML:

<Style TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}">
                    <ContentPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Blue"/>
        </Trigger>
    </Style.Triggers>
</Style>

后面的代码是这样的:

Style buttonStyle = new Style();

FrameworkElementFactory contentBorder = new FrameworkElementFactory(typeof(Border));
contentBorder.AppendChild(new FrameworkElementFactory(typeof(ContentPresenter)));
contentBorder.SetBinding(Border.BackgroundProperty, new Binding { RelativeSource = RelativeSource.TemplatedParent, Path = new PropertyPath(nameof(Background)) });
ControlTemplate templateButton = new ControlTemplate(typeof(Button)) { VisualTree = contentBorder };
buttonStyle.Setters.Add(new Setter { Property = Button.TemplateProperty, Value = templateButton });

Trigger styleTrigger = new Trigger { Property = Button.IsMouseOverProperty, Value = true };
styleTrigger.Setters.Add(new Setter { Property = Button.BackgroundProperty, Value = Brushes.Blue });
buttonStyle.Triggers.Add(styleTrigger);

createPlaylist.Style = buttonStyle;