//
int comma = s.IndexOf(',');
if (comma != -1)
{
// now that we have the comma, get
// the last name.
string last = s.Substring(0, comma);
int paren = s.LastIndexOf('(');
if (paren != -1 && s.LastIndexOf(')') == s.Length - 1)
{
// pick up the first name
string first = s.Substring(comma + 1, paren - comma - 1);
// get the age
int age = Int32.Parse(
s.Substring(paren + 1,
s.Length - paren - 2));
Person p = new Person();
p.Age = age;
p.LastName = last.Trim();
p.FirstName = first.Trim();
return p;
}
}
}
catch {}
// if we got this far, complain that we
// couldn't parse the string
//
throw new ArgumentException(
"Can not convert '" + (string)value +
"' to type Person");
}
return base.ConvertFrom(context, info, value);
}
public override object ConvertTo(
ITypeDescriptorContext context,
CultureInfo culture,
object value,
Type destType)
{
if (destType == typeof(string) && value is Person)
{
Person p = (Person)value;
// simply build the string as "Last, First (Age)"
return p.LastName + ", " +
p.FirstName + " (" + p.Age.ToString() + ")";
}
return base.ConvertTo(context, culture, value, destType);
}
}
现在看看我们的Person属性在指定了PersonConverter类型转换器之后,既可以展开,又可以通过两种方式来操作了:直接修改和使用子属性。
图3. 实现展开的TypeConverter
要使用上面的代码,我们就生成一个UserControl并且写下如下的代码:
private Person p = new Person();
public Person Person
{
get
{
return p;
}
set
{
this.p = value;
}
} |