如何将标签的Text属性绑定到ComboBox的.SelectedValue属性,并在该值更改时更新?

时间:2014-12-20 01:14:32

标签: .net winforms data-binding combobox datasource

我有一个ComboBox,它绑定到一个不断变化的用户列表。该列表可以根据用户的过滤器首选项进行更改。 ComboBox本身只显示用户名,但我有几个标签,我想显示在ComboBox中选择的用户的各种值。

我已经注意到它不起作用,因为当我设置过滤器什么都不返回时,组合框应该被赋予一个虚拟数据源(一个简单的匿名对象,其属性值符合组合框的标准。 DisplayMember属性,以及绑定标签的值。

我希望每当用户从ComboBox中选择另一个用户时,标签文本就会改变。

我知道将标签绑定到ComboBox.SelectedValue不起作用的原因是因为它只是在设置绑定时将它们的属性绑定到对象的属性。我觉得情况确实如此。

我知道这可能不是理想的解决方法(可能只是在ValueChanged事件中添加一个事件处理程序并将值数据读入标签中),但是,真的比任何事情更有趣否则,是否有可能实现我的目标?

编辑:

以下是一些相关代码:

//Assigning Combobox Datasource
List<TableEntries.User> Users =
    Tables.GetUsers( this.chkGetUnregistered.Checked, this.chkGetUnconfirmed.Checked );
if ( Users != null && Users.Count > 0 )
    this.cbxUserNames.DataSource = Users;

//DataBinding .Text properties of labels to .SelectedValue property of the ComboBox
this.lblCompany.DataBindings.Add("Text", this.cbxUserNames.SelectedValue, "UserCompany");
this.lblEmail.DataBindings.add("Text", this.cbxUserNames.SelectedValue, "UserEmail");
this.lblPhone.DataBindings.add("Text", this.cbxUserName.SelectedValue, "UserPhone");

我知道最简单的方法就是

this.cbxUserNames.SelectedValueChanged += (s,e) => {
    this.lblCompany.Text = (this.cbxUserNames.SelectedValue as TableEntries.User).UserCompany
    this.lblEmail.Text = ...
    this.lblPhone.Text = ...
};

这就是我现在拥有的方式。我知道它的工作方式是selectedvalue对象实际上没有改变,它只是消失了。该值的属性不会更改。所以我希望我能找到一种方法让标签“聪明”足以说“嘿,.SelectedValue属性改变了,我们应该看看新对象”

0 个答案:

没有答案