abelenky
abelenky

Reputation: 64730

New to WPF Data Binding

I'm new to WPF Data binding, and a bit stuck.
Apparently my textbox is not correctly bound to the data element I intend, and I cannot figure out why.

First in my MainWindow.xaml file, I declare an object:

<Window.Resources>
    <local:Aircraft x:Key="Aircraft"/>
</Window.Resources>

This creates an object of type Aircraft during MainWindow.InitializeComponent()
(I can verify this by putting a breakpoint on the constructor of Aircraft)

Class Aircraft is defined in a .cs file, with property Pilot which has property Weight, so that myAircraft.Pilot.Weight is an int.

Next, I try to bind a textbox to this property:

<TextBox Name="PICWeight" DataContext="{Binding Source={StaticResource Aircraft}, Path=Pilot.Weight}" />

The application compiles and runs, but when I put numeric text into the textbox, then move the focus to another textbox, I expect to see the setter for Pilot.Weight get called (I have a breakpoint on it). It doesn't.

I believe that there should be a default ValueConverter from String (from the textbox) to int (the type of the Weight property), and that textboxes should have default update-source event of LostFocus.

Am I specifying the binding properly?
Do I need to create a ValueConverter, or explicitly specify the update event?
Is there anything else I'm doing wrong?

Upvotes: 2

Views: 224

Answers (1)

John Bowen
John Bowen

Reputation: 24453

You need to bind the Text property, not just DataContext, like:

<TextBox Name="PICWeight" DataContext="{Binding Source={StaticResource Aircraft}}" Text="{Binding Path=Pilot.Weight}" />

or:

<TextBox Name="PICWeight" Text="{Binding Source={StaticResource Aircraft}, Path=Pilot.Weight}" />

Upvotes: 10

Related Questions