Reputation: 3185
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
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
Reputation: 18126
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
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