Winforms 将两个属性绑定到一个文本框文本
假设我有一个这样的类:Winforms 将两个属性绑定到一个文本框文本,winforms,data-binding,textbox,Winforms,Data Binding,Textbox,假设我有一个这样的类: class MyClass { ... (some more properties here) public int Min {get;set;} public int Max {get;set;} ... (some more properties here) } 现在我在设计器中放置了一个文本框,我希望它将最小值和最大值显示为用破折号分隔的文本。 例如,如果最小值=3,最大值=10,则文本框应显示“3-10”。 当文本被更改/绑定
class MyClass
{
... (some more properties here)
public int Min {get;set;}
public int Max {get;set;}
... (some more properties here)
}
现在我在设计器中放置了一个文本框,我希望它将最小值和最大值显示为用破折号分隔的文本。
例如,如果最小值=3,最大值=10,则文本框应显示“3-10”。
当文本被更改/绑定被更新时,它应该像这样解析字符串“3-10”:
class MyClass
{
... (some more properties here)
public int Min {get;set;}
public int Max {get;set;}
... (some more properties here)
}
将字符串拆分为“-”,并使用int.parse(…)解析这两个字符串
如果这不起作用(发生异常情况),我想以某种方式对此作出反应。例如,显示错误消息将起作用
我该怎么做?
VisualStudio设计器仅允许我将文本绑定到对象的一个属性。对于显示3-10,您可以编写
TextBoxName.Text=Min + "-" + Max;
并且,您可以引发异常并将MessageBox显示为:
try{
int.Parse(Min);
int.Parse(Max);
}
catch(Exception ae){
MessageBox.Show("Some error message");
}
编辑:
用于约束
textBoxName.DataBindings.Add("Text",this,"StringVariable");
//Text property,this form, name of the variable.
其中StringVariable是返回Min+“-”+Max的某个属性 是的,但我不想将该值直接指定给Text属性。我需要用数据绑定来解决它。