【问题标题】:Databinding a WPF Textbox in Winforms在 Winforms 中对 WPF 文本框进行数据绑定
【发布时间】:2012-08-21 09:15:17
【问题描述】:

我在 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# 中的解决方案都可以。

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    更新

    您的代码中有一个错误(或者只是一个拼写错误,这会导致逻辑错误)。
    您正在尝试将 TextBlock.TextProperty 绑定到 TextBox 控件上。

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

    【讨论】:

    • 我只是使用标准的绑定源,它的数据源设置为数据表。 bgsTasks.DataSource = TasksDataSet.Tasks
    • @Reafidy:我已经更准确地查看了您的代码并更新了我的答案。
    • 谢谢,你的正确那是一个错误。但是,它似乎仍然无法解决问题。文本框没有绑定到绑定源。我用普通文本框替换了 wpf 框,并使用我的普通数据绑定方法检查绑定是否适用于数据源。
    • @Reafidy:请在此处发布您完整的非工作代码示例。绑定没有魔法。另外,您是否在 VS 输出窗口中看到任何绑定错误?
    • 感谢您的耐心等待。我发现问题是我在设置绑定之后填充数据表。这适用于标准文本框,但不适用于 WPF 文本框。我必须先填充数据集,然后绑定文本框。你的回答和 cmets 真的很有帮助。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多