在Winforms中数据绑定WPF文本框

时间:2012-08-21 09:15:18

标签: c# .net wpf vb.net winforms

我在Winforms项目的元素主机中使用WPF文本框。

我想将此文本框数据绑定到绑定源,就像我使用标准winforms文本框一样:

    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#中的解决方案都很好。

1 个答案:

答案 0 :(得分:1)

试试这个:

<强>更新

您的代码中存在错误(或只是一个错误,导致逻辑错误) 您正尝试在 TextBox 控件上绑定 TextBlock .TextProperty。

应该有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;

原因是这些依赖属性(和控件)不同,尽管它们具有相似的名称。

如果它不是拼写错误,那么我建议你阅读WPF依赖属性机制here