【问题标题】:C# WPF Binding Programmatically Lead to NULL [duplicate]C# WPF 绑定以编程方式导致 NULL [重复]
【发布时间】:2021-07-31 11:11:33
【问题描述】:

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

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; }
    }
}

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

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

    binding.Source = s;
    

    绑定将正确解析。

    【讨论】:

    • 如果有多个属性,编译器如何解析绑定?我必须像绑定的属性一样命名它们?
    • 不知道我的问题是否正确,但通常属性是绑定的Path(您可以像在代码中那样将其传递给绑定的构造函数) Source 是具有该属性的对象。如果要绑定到同一对象的 mutliprl 属性,源始终相同(代码中的 s)并且属性名称转到 ctor:var b1 = new Binding("Background"); b1.Source = s; var b2 = new Binding("Foreground"); b2.Source = s; //if you had a property named Foreground in 'Something'
    • 完美,我明白了! TY
    猜你喜欢
    • 2021-09-06
    • 2011-10-22
    • 2016-10-24
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多