在 Winforms 中数据绑定 WPF 文本框
我在 Winforms 项目的元素宿主中使用 WPF 文本框.
I am using a WPF textbox inside an element host in a Winforms project.
我想将此文本框数据绑定到绑定源,就像我对标准 winforms 文本框所做的那样:
I would like to databind this textbox to a bindingsource as I do with the standard winforms textbox like so:
Me.tbxCorrectiveAction.DataBindings.Add("Text", bgsTasks, "CorrectiveAction", False)
这是我尝试过的:
Dim host As New System.Windows.Forms.Integration.ElementHost()
Dim wpfTextBox As New System.Windows.Controls.TextBox()
wpfTextBox.SpellCheck.IsEnabled = True
host.Dock = DockStyle.Fill
host.Child = wpfTextBox
Me.Panel8.Controls.Add(host)
Dim binCorrectiveAction As New System.Windows.Data.Binding("CorrectiveAction")
binCorrectiveAction.Source = bgsTasks
wpfTextBox.SetBinding(System.Windows.Controls.TextBlock.TextProperty, binCorrectiveAction)
VB 或 C# 中的解决方案都很好.
Solutions in either VB or C# are fine.
试试这个:
更新.
您的代码中存在错误(或者只是拼写错误,导致逻辑错误).
您正在尝试将 TextBlock.TextProperty 绑定到 TextBox 控件上.
There's an error in your code (or just a typo, which causes a logical error).
You're trying to bind TextBlock.TextProperty on a TextBox control.
应该有TextBox.TextProperty
:
var dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(Int32));
dataTable.Columns.Add("Name", typeof(String));
dataTable.Rows.Add(1, "John");
dataTable.Rows.Add(2, "Mary");
dataTable.Rows.Add(3, "Peter");
dataTable.Rows.Add(4, "Helen");
var bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
var binding = new System.Windows.Data.Binding("Name");
binding.Source = bindingSource;
binding.UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
var textBox = new System.Windows.Controls.TextBox();
textBox.SpellCheck.IsEnabled = true;
textBox.SetBinding(System.Windows.Controls.TextBox.TextProperty, binding);
elementHost1.Child = textBox;
原因是这些依赖属性(和控件)不同,尽管它们具有相似的名称.
The reason is that these dependency properties (and controls) are differ, in spite of they have similar names.
如果不是拼写错误,那么我建议您阅读 WPF 依赖属性机制 此处.
If it isn't a typo, then I recommend you to read about WPF dependency properties mechanism here.