0

I'm trying to set the Background Property of an in-code generated label to a custom object property. Well this code don't work. The label appear correctly but the background property is a null value. Where I'm wrong?

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; }
    }
}
KaT_624
  • 11
  • 2

1 Answers1

0

The source of a Binding is the object that owns the bound property, not the value of the property. If you change it to:

binding.Source = s;

the binding will resolve properly.

lidqy
  • 1,891
  • 1
  • 9
  • 11
  • How the compiler resolve the bindings if there are multiples Properties? I have to name them like the binded Property? – KaT_624 Jul 31 '21 at 11:48
  • Don't know if I got your question correctly, but in general the properties are the `Path` of the binding (which you can pass to the constructor of the binding as you did in your code) and the Source is the object that has that property. If you want to bind to mutliprl properties of the same object, the source is always the same (`s` in your code) and the property name goes to the 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'` – lidqy Jul 31 '21 at 11:55
  • 1
    Perfect, I've Got it! TY – KaT_624 Jul 31 '21 at 12:15