user472875
user472875

Reputation: 3185

How to debug databinding

I'm new to data-binding and I am having a hard-time setting it up for my WPF application:

I have a class Test which implements INotifyPropertyChanged and a property Text.

When I do this in the code-behind:

Binding b = new Binding("Text");
b.Source = Test;
label1.SetBinding(ContentProperty, b);

everything works great.

When I do the same thing in XAML:

Content="{Binding Source=Window.Test, Path=Text}"

The label content does not update.

I would like to avoid having to do this in the code-behind, what am I doing wrong?

Upvotes: 0

Views: 896

Answers (3)

brunnerh
brunnerh

Reputation: 185445

what am I doing wrong?

You are making unfounded assumptions about how something ought to work about which you do not have much of a clue. You are dealing with two fundamentally different languages here and just because you want WPF to interpret Window.Test as a reference to some specific window you had in mind does not make it so.

XAML is fundamentally string-based, for the most part strings are converted to primitive types like ints and doubles, e.g. when you set the height of a control you pass a string to a property of type double. The XAML parser knows via reflection that the property is of type double and tries to convert the string (using a default value converter if no other has been specified). Now what do you think happens if a property is of type object? What is the parser to do? Well, it is not going to do anything as a string is already an object.

Guess what type Binding.Source has and what the source object of your binding will be when you write Window.Test...

Upvotes: 0

For simplicity, set the window DataContext to your Test instance:

public partial class MainWindow : Window
{   
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new Test
            {
                Text = "Hello, World!"
            };
    }
}

Then declare databinding in XAML:

Content="{Binding Path=Text}"

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292695

The easiest solution is to give a name to the Window in XAML (e.g. root) and use ElementName to define the binding source:

Content="{Binding ElementName=root, Path=Test.Text}"

Upvotes: 1

Related Questions