C# WPF 绑定以编程方式导致 NULL

C# WPF Binding Programmatically Lead to NULL

我正在尝试将代码内生成标签的背景 属性 设置为自定义对象 属性。那么这段代码不起作用。标签正确显示,但背景 属性 为空值。我哪里错了?

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();

        Something s = new Something();

        Label testLabel = new()
        {
            Content = "TEST",
            Margin = new Thickness(5),
            Padding = new Thickness(5)
        };

        Binding binding = new("Background");
        binding.Source = s.Background;

        testLabel.SetBinding(BackgroundProperty, binding);

        stackpanel.Children.Add(testLabel);

    }
}

public class Something
{
    private Brush _background = Brushes.Green;

    public Brush Background
    {
        get { return _background; }
        set { _background = value; }
    }
}

绑定的源是拥有绑定 属性 的对象,而不是 属性 的值。 如果将其更改为:

binding.Source = s;

绑定将正确解析。