问题一:
我有一个简单的winforms应用程序,我想将Person.Name属性绑定(bind)到文本框。名称的类型为StringField。我最初将Name属性定义为String。数据绑定(bind)在诸如String之类的值类型上非常有用。我希望StringField.Value属性是StringField的默认属性。我想在文本框中而不是文本“FieldApp.StringField”中看到StringField.Value的值。
问题2:
我希望能够使用运算符=将字符串分配给StringField。此分配将导致设置StringField.Value成员。
能做到吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FieldApp
{
public class StringField
{
public string Value { get; set; }
}
public class Person
{
//private String _Name;
//public String Name
//{
// get { return _Name; }
// set { _Name = value; }
//}
//public Person(string name)
//{
// Name = name;
//}
private StringField _Name;
public StringField Name
{
get { return _Name; }
set { _Name = value; }
}
public Person(string name)
{
Name = new StringField();
Name.Value = name;
}
}
public partial class FieldAppForm : Form
{
Person person = new Person("steve");
public FieldAppForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//our form contains a button1 and textBox1
//this compiles
person.Name.Value = "steve";
//this does not. Is there anyway to accomplish this?
person.Name = "steve";
//steve appears in the textbox
textBox1.DataBindings.Add("Text", person, "Name.Value");
//FieldApp.StringField appears in the textbox
textBox1.DataBindings.Add("Text", person, "Name");
}
}
}
最佳答案
您可以创建一个隐式运算符重载。然后,您可以像这样从字符串创建StringField
:
StringField field = "value of new object";
string value=(string)field;
知道这将创建一个新的
StringField
对象。我不一定会建议您这样做。[System.Diagnostics.DebuggerDisplay("{Value}")]
public class StringField
{
public string Value { get; set; }
public static implicit operator StringField(string s)
{
return new StringField { Value = s };
}
public static explicit operator string(StringField f)
{
return f.Value;
}
public override string ToString()
{
return Value;
}
}