[英]New to WPF Data Binding
I'm new to WPF Data binding, and a bit stuck. 我是WPF数据绑定的新手,有点卡住了。
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: 首先在我的
MainWindow.xaml
文件中,我声明了一个对象:
<Window.Resources>
<local:Aircraft x:Key="Aircraft"/>
</Window.Resources>
This creates an object of type Aircraft during MainWindow.InitializeComponent()
这在
MainWindow.InitializeComponent()
期间创建了Aircraft类型的对象
(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
. Class
Aircraft
在.cs
文件中定义,属性Pilot
具有属性Weight
,因此myAircraft.Pilot.Weight
是一个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). 应用程序编译并运行,但是当我将数字文本放入文本框中,然后将焦点移动到另一个文本框时,我希望看到
Pilot.Weight
的setter
被调用(我有一个断点)。 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
. 我相信应该有一个默认的ValueConverter从String(从文本框)到int(Weight属性的类型),并且该文本框应该具有
LostFocus
默认更新源事件。
Am I specifying the binding properly? 我是否正确指定了绑定?
Do I need to create a ValueConverter, or explicitly specify the update event? 我是否需要创建ValueConverter,或明确指定更新事件?
Is there anything else I'm doing wrong? 还有什么我做错了吗?
You need to bind the Text property, not just DataContext, like: 您需要绑定Text属性,而不仅仅是DataContext,如:
<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}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.