我正在使用 winforms,并且有一个代表 IQueryable 的组合框。组合框下方是一系列文本框,我希望将它们绑定到组合框中当前选择的文本框。
这是我的代码。
public partial class TestForm : Form
{
public DataClassesDataContext DataContext;
public IQueryable<T> datasource;
// Ctor
public TestForm()
{
InitializeComponent();
// L2S data context
this.DataContext = new DataClassesDataContext();
// Get the variable for the data source
this.datasource = this.DataContext.Ts;
// setup the binding for the combobox
this.comboBox1.DataSource = this.datasource;
this.comboBox1.DisplayMember = "Description";
this.comboBox1.ValueMember = "Id";
// assign the databindings of the text boxes to the selectedItem of the combo box
// this is where the problem is, afaik
TId.DataBindings.Add(new Binding("Text", this.comboBox1.SelectedItem, "Id"));
TUser.DataBindings.Add(new Binding("Text", this.comboBox1.SelectedItem, "User"));
TDescription.DataBindings.Add(new Binding("Text", this.comboBox1.SelectedItem, "Description"));
}
这样做会绑定所有内容,当我更改文本框中的值时,它会很好地更新组合框中最初选定的项目。即使当我更改描述时,它也会更新 drop don 中显示的文本,这一切都很棒。
但是,当我从下拉列表中选择不同的项目时,文本框不会绑定到新选择的项目,而是保持绑定到旧的项目。
每次组合框中的选择发生变化时,我是否需要删除并重新添加绑定?
我原来的答案是错误的,诚然,我并不完全理解这里发生的一切,但我有一个有效的解决方案。
基本上你需要抓住BindingManagerBase
来自BindingContext
并使用它来强制每个SelectedItemChanged
event.
public partial class TestForm : Form
{
public DataClassesDataContext DataContext;
public IQueryable<T> datasource;
private BindingManagerBase bmComboBoxSelectedItem;
// Ctor
public TestForm()
{
InitializeComponent();
// L2S data context
this.DataContext = new DataClassesDataContext();
// Get the variable for the data source
this.datasource = this.DataContext.Ts;
// setup the binding for the combobox
this.comboBox1.DataSource = this.datasource;
this.comboBox1.DisplayMember = "Description";
this.comboBox1.ValueMember = "Id";
// assign the databindings of the text boxes to the selectedItem of the combo box
// this is where the problem is, afaik
TId.DataBindings.Add(new Binding("Text", this.comboBox1, "SelectedItem.Id"));
TUser.DataBindings.Add(new Binding("Text", this.comboBox1, "SelectedItem.User"));
TDescription.DataBindings.Add(new Binding("Text", this.comboBox1, "SelectedItem.Description"));
bmComboBoxSelectedItem = this.BindingContext[this.comboBox1, "SelectedItem"];
}
// make sure you assign this event on the forms designer or your preferred method
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
bmCustomers.ResumeBinding();
}
}
This MSDN 文章 http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.aspx帮了很多忙。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)