在 DateMember 的路径有多层的 WinForms 中绑定

Binding in WinForms where DateMember's path has multiple layers

通用绑定在 WinForms 中工作正常,但如果我的绑定的数据成员有多层,我就会遇到问题。

我将 TextBox 的 Text-属性 绑定到我的 SubViewModel 的 属性 'CurrentText'。

这是我有问题的绑定:

myTextBox.DataBindings.Add(nameof(myTextBox.Text), MyViewModel, "SubViewModel.CurrentText", true, DataSourceUpdateMode.OnPropertyChanged, null);

我认为有问题的部分是第三个参数"SubViewModel.CurrentText".

顺便说一句。当调用 setter 时,两个属性(SubViewModel 和 CurrentText)都会引发 "INotifyPropertyChanged"。

感谢您的付出!

我找到了一个有效的解决方案。第二个绑定参数 "dataSource" (MyViewModel) 不应来自任何类型,而应来自 "BindingSource"。将 MyViewModel 包装到 BindingSource 后一切正常。

var bindingSource = new BindingSource(this, nameof(MyViewModel));
myTextBox.DataBindings.Add(nameof(myTextBox.Text), bindingSource, "SubViewModel.CurrentText", true, DataSourceUpdateMode.OnPropertyChanged, null);

该解决方案有效,但仅适用于一层(例如“SubViewModel.CurrentText”)。 如果有第三层,那么它就不再起作用了(例如“SubViewModel.SubSubViewModel.CurrentText”)。

有人有想法吗?

var bindingSource = new BindingSource(this, nameof(MyViewModel));
myTextBox.DataBindings.Add(nameof(myTextBox.Text), bindingSource, "SubViewModel.SubSubViewModel.CurrentText", true, DataSourceUpdateMode.OnPropertyChanged, null);

2020 年 4 月 16 日更新:

我现在使用自定义解决方法解决了这个问题。

使用BindingSource 作为DataSource 支持两层路径绑定。但它遭受了三层或更多层。为了检测这种情况下的变化,我现在手动观察成员。

我的解决方案观察 ViewModel 上的绑定值。如果任何 属性 已更改,则方法 ResetBindings 将在 BindingSource 上调用(请参阅 MainView[= 后面的代码38=]).

我在 github:

的单独分支 (CustomWorkaround) 中与您分享我的解决方法

https://github.com/Der-Kraken/Kraken.WinFormsBinding/commit/08412e9bc05e6430e4f9624a29b6efe9e98675bd