如何使用DataBindings在具有不同数据类型的属性之间进行绑定? [英] How to bind between properties with different data type using DataBindings?

查看:74
本文介绍了如何使用DataBindings在具有不同数据类型的属性之间进行绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚学到了一些关于DataBindings的知识.在具有相同数据类型的属性(例如bool)之间进行绑定时,我可以找到帮助,但是当属性具有不同数据类型(例如bool和string)时,我很难做到这一点.
例如,我希望当组合框的选定文本为启用"时,面板的启用"属性应为真值.
我该怎么办?
非常感谢您!

I''ve just learned a little on DataBindings. I can find help with it when binding between properties with the same data type (such as bool), but it''s hard for me to do that when properties have different data types (such as bool and string).
For example, I want when the selected text of a combobox is "Enable", the "Enabled" property of a panel should have true value.
How can I do that?
Thank you so much!

推荐答案

现在我知道您的意思了.很抱歉在我的第一个解决方案中感到困惑.
具有不同类型的DataBinding非常容易实现.

在示例中,我使用了一个TextBox和一个CheckBox.当TextBox.Text读取为"enabled"时,将选中CheckBox.


Now I know what you mean. Sorry for confusion in my first solution.
The DataBinding with different types is quite easy to accomplish.

In the example I''m using a TextBox and a CheckBox. CheckBox will be checked when TextBox.Text reads "enabled".


public Form1()
{
    InitializeComponent();
    Binding b = new Binding("Checked", textBox1, "Text");
    b.Format += new ConvertEventHandler(b_Format);
    checkBox1.DataBindings.Add(b);
}
void b_Format(object sender, ConvertEventArgs e)
{
    e.Value = e.Value.ToString() == "enabled" ? true : false;
}



希望这就是您要寻找的东西



Hope this is what you were looking for


SelectedIndexChanged事件中,您可以这样做

In the SelectedIndexChanged event you could do this

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    panel1.Enabled = (comboBox1.SelectedItem.ToString() == "enabled");
}



------
正如您在评论中指出的那样,这不是解决方案,这里是更新:

假设您正在谈论这种绑定:
textBox1.DataBindings.Add(new Binding("Text", comboBox1, "SelectedItem"));

无法在属性之间转换类型,因为它们是通过Binding(string,object,string);按名称选择的.



------
As you stated in you comment that this is not the solution, here''s the update:

Assuming you''re talking about this kind of binding:
textBox1.DataBindings.Add(new Binding("Text", comboBox1, "SelectedItem"));

There''s no way to convert types between properties because they get choosen by name through Binding(string,object,string);


这篇关于如何使用DataBindings在具有不同数据类型的属性之间进行绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆