Windows 窗体组合框 - 数据绑定到多个属性
我在将数据绑定到组合框的 SelectedValue 和 Text 属性时遇到问题。这是相关的代码片段:
DataTable dt1 = DataAccess.GetLoanPurposes();
ddLoanPurpose.DisplayMember = "Name";
ddLoanPurpose.ValueMember = "Value";
ddLoanPurpose.DataBindings.Add("Text", _scenario, "LoanPurposeString", false);
ddLoanPurpose.DataBindings.Add("SelectedValue", _scenario, "LoanPurpose", false);
ddLoanPurpose.DataSource = dt1;
我可以绑定到 Text 或 SelectedValue,一切都运行良好。当我尝试绑定到两者时,麻烦就来了。只有第一个数据绑定有效(上例中的 Text 到 LoanPurposeString)。如果我切换数据绑定的顺序...
ddLoanPurpose.DataBindings.Add("SelectedValue", _scenario, "LoanPurpose", false);
ddLoanPurpose.DataBindings.Add("Text", _scenario, "LoanPurposeString", false);
...然后我会丢失 Text 到 LoanPurposeString 的绑定,但现在 SelectedValue 绑定到 LoanPurpose。所以我的问题是双重的:为什么两个绑定都不连接到我的 _scenario 对象以及为什么顺序很重要?
I am having trouble databinding to a Combobox's SelectedValue and Text properties. Here is the relevant code snippet:
DataTable dt1 = DataAccess.GetLoanPurposes();
ddLoanPurpose.DisplayMember = "Name";
ddLoanPurpose.ValueMember = "Value";
ddLoanPurpose.DataBindings.Add("Text", _scenario, "LoanPurposeString", false);
ddLoanPurpose.DataBindings.Add("SelectedValue", _scenario, "LoanPurpose", false);
ddLoanPurpose.DataSource = dt1;
I can bind to either Text or SelectedValue and everything works brilliantly. The trouble comes when I try to bind to both. Only the first Databinding works (Text to LoanPurposeString in the example above). If I switch the order of the Databinding...
ddLoanPurpose.DataBindings.Add("SelectedValue", _scenario, "LoanPurpose", false);
ddLoanPurpose.DataBindings.Add("Text", _scenario, "LoanPurposeString", false);
...then I lose the binding of Text to LoanPurposeString but now SelectedValue binds to LoanPurpose. So my question is twofold: Why don't both of the bindings wire up to my _scenario object and why does the order matter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎不支持对两个不同属性的数据绑定(至少不基于我的研究)。在此特定实例中,最佳解决方案是将 _scenario 对象中的单独属性(LoanPurpose 和 LoanPurposeString)合并为单个 KeyValuePair 属性。
我只需要确保数据源中的 ValueMember 变量是 KeyValuePair。所以像......
绑定语法将与我原来的问题相同,唯一的区别是 ValueMember 现在是 KeyValuePair 对象而不是字符串。
Databinding to two different properties doesn't seem to be supported (at least not based on my research). In this particular instance, the best solution is to combine the separate properties in my _scenario object (LoanPurpose and LoanPurposeString) into a single KeyValuePair property.
I just need to make sure that the ValueMember variable in the DataSource is a KeyValuePair. So something like...
The binding syntax will be the same as in my original question, the only difference is that the ValueMember is now a KeyValuePair object instead of a string.