开发者

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 anythi开发者_如何学Gong else I'm doing wrong?


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}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜