【发布时间】:2015-02-26 13:39:29
【问题描述】:
我在 WPF 中遇到数据绑定问题,这是我的示例类:
public class testClass
{
public Size testInnerSize;
public testClass()
{
testInnerSize = new Size(66, 99);
}
}
我想将表单中的 TextBox 绑定到 testInnerSize 的属性,比如说宽度。所以我将此文本框的 DataContext 设置为 testClass 对象并在 XAML 中:
<TextBox Text="{Binding Path=testInnerSize.Width }" Name="textBox3" (...)
但它不起作用,文本框是空的,而不是值 66。另一方面,当我将 DataContext 设置为 testObject.testInnerSize 时,该值显示在文本框中,但之后它不会在对象中更新文字修改。
所以问题是:如何双向绑定作为另一个对象属性的 Size 对象的 Width 属性?
用于测试的完整代码:
public partial class testpage : Page
{
public Size testSize;
testClass testObject = new testClass();
public testpage()
{
InitializeComponent();
testSize = new Size(6, 9);
textBox2.DataContext = testSize;
textBox3.DataContext = testObject;
}
private void textChanged(object sender, TextChangedEventArgs e)
{
MessageBox.Show(testObject.testInnerSize.Width + " " + testObject.testInnerSize.Height, "", MessageBoxButton.OK);
}
}
public class testClass
{
public Size testInnerSize;
public testClass()
{
testInnerSize = new Size(66, 99);
}
}
XAML 绑定:
<TextBox Text="{Binding Path=Width }" Name="textBox2" />
<TextBox Text="{Binding Path=testInnerSize.Width }" Name="textBox3" TextChanged="textChanged" />
更新 1
现在我已经检查过了,它不依赖于作为 testClass 对象的子对象 - testSize 属性已绑定,因此其文本框显示正确的值,但 testSize.Width 值没有被更新。要查看它,只需添加:
private void text1Changed(object sender, TextChangedEventArgs e)
{
MessageBox.Show(testSize.Width + " " + testSize.Height, "", MessageBoxButton.OK);
}
TextChanged 事件的处理程序。
【问题讨论】:
-
将您的
testInnerSize声明为属性。public Size testInnerSize{get;set;}
标签: c# wpf xaml data-binding size