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

问题描述

我有在WPF数据绑定的一个问题,这是我的示范类:

I have a problem with databinding in WPF, here's my exemplary class:

public class testClass
{
    public Size testInnerSize;

    public testClass()
    {
        testInnerSize = new Size(66, 99);
    }
}



我想一个文本框在我的形式向绑定testInnerSize的财产,让我们说宽度。所以我设置该文本框的的DataContext到TestClass的对象,并在XAML:

I want to bind a TextBox in my form to the property of testInnerSize, let's say Width. So I'm setting the DataContext of this textbox to the testClass object and in XAML:

<TextBox Text="{Binding Path=testInnerSize.Width }" Name="textBox3" (...)

但事实并非如此工作中,文本框为空,而不必在另一方面值66,当我设置在DataContext为testObject.testInnerSize显示在文本框中的值,但它不是在文本修改后的对象进行更新。

But it does not work, the textbox is empty instead of having value 66. On the other hand, when I set the DataContext to testObject.testInnerSize the value is displayed in a textbox, yet it is not updated in the object after text modification.

所以,问题是:我怎么能双向绑定一个Size对象是另一个对象的属性的Width属性。

So the question is: how can I two-way bind the Width property of a Size object that is a property of another object?

用于测试的完整代码:

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绑定:

XAML binding:

    <TextBox Text="{Binding Path=Width }" Name="textBox2" />
    <TextBox Text="{Binding Path=testInnerSize.Width }"  Name="textBox3" TextChanged="textChanged" />



更新1

现在我已经检查,它不依赖于作为对象的TestClass的子对象 - 在testSize属性绑定所以它的文本框会显示一个合适的值,但testSize.Width值不会被更新。要看到它只需添加:

Now I have checked and it does not depend on being a subobject of the testClass object - the testSize property is binded so its textbox displays a proper value, but the testSize.Width value is not being updated. To see it just add:

    private void text1Changed(object sender, TextChangedEventArgs e)
    {
        MessageBox.Show(testSize.Width + " " + testSize.Height, "", MessageBoxButton.OK);
    }



处理程序,以一个TextChanged事件。

handler to a TextChanged event.

推荐答案

您testInnerSize不是属性。这是一个领域。属性有get和set访问。你也应该实现INotifyPropertyChanged。

Your testInnerSize is not a property. It's a field. Properties have get and set accessors. Also you should implement INotifyPropertyChanged.

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

09-03 08:18