c# - 在 WPF 中以编程方式为动态组合框中的动态文本框设置数据绑定(bind)

标签 c# wpf xaml combobox textbox

这部分有效。

在我的 C#.NET WPF XAML 中,我有一个 static ComboBox 和一个 static TextBox。 TextBox 显示同一 DataTable 中的另一列(在 ComboBox 的 ItemSource 中)。 “rr_code”列是公司名称列,“rr_addr”列是地址列。

<ComboBox x:Name="CompanyComboBox1" IsEditable="True" IsTextSearchEnabled="True" IsSynchronizedWithCurrentItem="False"/>
<TextBox x:Name="StreetTextBox1" DataContext="{Binding SelectedItem, ElementName=CompanyComboBox1}" Text="{Binding rr_addr}" IsManipulationEnabled="True"\>

组合框以编程方式从数据表中的列中读取:

 CompanyComboBox1.ItemsSource = Rails.DefaultView; // Rails is a DataTable
 CompanyComboBox1.DisplayMemberPath = "rr_code"; // column name for company name

这部分不起作用

问题是,我现在有一个“添加公司”按钮,可以在 StackPanel 中动态创建一个新表单,并具有此确切的功能。 ComboBox 完全按照预期工作。这是我到目前为止所拥有的:

ComboBox companyComboBox = new ComboBox();
companyComboBox.ItemsSource = Rails.DefaultView;
companyComboBox.IsEditable = true;
companyComboBox.IsTextSearchEnabled = true;
companyComboBox.DisplayMemberPath = "rr_code";

问题出在 TextBox 中,当我更改动态 companyComboBox 时,它没有更新,所以我确信它与绑定(bind)有关。

TextBox streetTextBox = new TextBox();
streetTextBox.DataContext = companyComboBox;
Binding b = new Binding("rr_addr");
b.Mode = BindingMode.Default;
b.Source = companyComboBox.SelectedItem;
streetTextBox.SetBinding(ComboBox.SelectedItemProperty, b);

设置文本框 streetTextBox 绑定(bind)的正确方法是什么?

最佳答案

纯 C# 中此特定 XAML + C# 数据绑定(bind)的代码隐藏等效项是:

ComboBox companyComboBox = new ComboBox();
companyComboBox.ItemsSource = Rails.DefaultView;  // Rails being DataTable
companyComboBox.IsEditable = true;
companyComboBox.IsTextSearchEnabled = true;
companyComboBox.DisplayMemberPath = "rr_code";

Binding b = new Binding("SelectedItem.rr_addr");  // The selected item's 'rr_addr' column ...
b.Source = companyComboBox;                       // ... of the companyComboBox ...

TextBox streetTextBox = new TextBox();    
streetTextBox.SetBinding(TextBox.TextProperty,b); // ... is bound to streetTextBox's Text property.

错误出现在最后一行。 SetBinding 需要具有目标的属性,而不是源的属性。此外,绑定(bind)声明需要“SelectedItem”。由于某种原因。

关于c# - 在 WPF 中以编程方式为动态组合框中的动态文本框设置数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397094/

相关文章:

c# - 如何返回对结构列表中特定结构的引用?

c# - 在 XP 上,如何使工具提示显示在半透明表单上方?

c# - 使用 WPF 和 MVVM 实现大型设置对话框的方法

c# - WPF - 绑定(bind)到另一个对象内的自定义对象的属性

c# - 将 xamarin.forms.shell 重置为后退按钮上的初始页面

c# - 如何从另一个线程中的表单关闭新线程上的表单?

c# - WPF数据网格箭头(右/左)键导航异常

c# - 无法从 DataGrid 问题中转换 .SelectedItems

c# - 如何在 Windows Phone 中旋转相机查看器?

c# - asp.net中通过javascript获取控件Id