数据绑定是否支持Windows窗体中的嵌套属性?

Mak*_*kov 10 c# data-binding winforms

我正在Windows窗体中编写测试应用程序.它有一个简单的TextBox形式,需要实现DataBinding.我已经实现了FormViewModel类来保存我的数据,并且我的业务数据有一个类 - TestObject.

业务数据对象:

public class TestObject : INotifyPropertyChanged
{
    private string _testPropertyString;
    public string TestPropertyString
    {
        get
        {
            return _testPropertyString;
        }
        set
        {
            if (_testPropertyString != value)
            {
                _testPropertyString = value;
                RaisePropertyChanged("TestPropertyString");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

视图模型:

public class FormViewModel : INotifyPropertyChanged
{
    private TestObject _currentObject;
    public TestObject CurrentObject
    {
        get { return _currentObject; }
        set
        {
            if (_currentObject != value)
            {
                _currentObject = value;

                RaisePropertyChanged("CurrentObject");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

属性:

private FormViewModel _viewModel;
public FormViewModel ViewModel
{ 
    get
    {
        if (_viewModel == null)
            _viewModel = new FormViewModel();

        return _viewModel;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以现在我正在尝试将我的数据绑定到TextBox,如下所示:

TextBox.DataBindings.Add("Text", ViewModel, "CurrentObject.TestPropertyString");
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,它不起作用!当我更改CurrentObject或更改TestPropertyString属性时,没有任何更改.

但是当我使用时,它很有效:

TextBox.DataBindings.Add("Text", ViewModel.CurrentObject, "TestPropertyString");
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:数据绑定是否支持嵌套属性?

谢谢你的解释!

Lar*_*ech 8

Databinding在.NET 4.0中更改了该行为.您的代码适用于.NET 3.5.我发现此问题发布在Microsoft Connect:.Net 4.0简单绑定问题

这是为我工作的解决方法.使用a BindingSource作为数据对象:

BindingSource bs = new BindingSource(_viewModel, null);

//textBox1.DataBindings.Add("Text", _viewModel, "CurrentObject.TestPropertyString");
textBox1.DataBindings.Add("Text", bs, "CurrentObject.TestPropertyString");
Run Code Online (Sandbox Code Playgroud)