新的WPF数据绑定 [英] New to WPF Data Binding

查看:100
本文介绍了新的WPF数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的WPF数据绑定,有点卡住了。结果
显然我的文本框不正确绑定到数据元素我打算,我想不通为什么。

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.

首先在我的 MainWindow.xaml 文件,我宣布一个对象:

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

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

这期间 MainWindow.InitializeComponent()结果

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

飞机(我可以把飞机上的构造函数断点验证) 的.cs 文件中定义,财产试验拥有财产重量,使 myAircraft.Pilot.Weight INT

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

应用程序编译和运行,但是当我把数字文本到文本框中,然后将焦点移到另一个文本框,我希望看到的二传手 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.

我认为,应该从字符串默认ValueConverter(从文本框)为int(Weight属性的类型),以及文本框应该有引发LostFocus 的默认的更新源事件。

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.

我是指定绑定是否正确?结果
我需要创建一个ValueConverter,或明确指定更新事件?结果
还有什么我做错了?

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?

推荐答案

您需要将文本属性绑定,而不仅仅是DataContext的,如:

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

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

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

这篇关于新的WPF数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆