C# 允许对复杂类进行字符串编辑
我创建了一个类来表示只有一小时和一分钟的时间,名为C# 允许对复杂类进行字符串编辑,c#,wpf,C#,Wpf,我创建了一个类来表示只有一小时和一分钟的时间,名为time。我重载了该类的ToString()方法。我在DataGrid中显示具有Time属性的类,使用DataGridTextColumn显示Time。我只是看着作品,但我不能编辑它。我在time类中添加了一个构造函数,它接受一个字符串,没有帮助。我需要实现什么才能使其工作 上课时间: public class Time { public Time() { } /// <summary> /// the h
time
。我重载了该类的ToString()
方法。我在DataGrid中显示具有Time
属性的类,使用DataGridTextColumn
显示Time
。我只是看着作品,但我不能编辑它。我在time类中添加了一个构造函数,它接受一个字符串,没有帮助。我需要实现什么才能使其工作
上课时间:
public class Time
{
public Time() { }
/// <summary>
/// the hour
/// </summary>
public int Hour
{
get;
set;
}
/// <summary>
/// the minuets
/// </summary>
public int Minutes
{
get;
set;
}
/// <summary>
/// the time in format hh:mm
/// </summary>
public string time
{
get { return String.Format("{0:00}:{1:00}", Hour, Minutes); }
set
{
string[] spl = value.Split(':');
Hour = Int32.Parse(spl[0]);
Minutes = Int32.Parse(spl[1]);
}
}
public override string ToString()
{
return time;
}
}
公共课时间
{
公共时间(){}
///
///时刻
///
公共整数小时
{
收到
设置
}
///
///小步舞曲
///
公共整数分钟
{
收到
设置
}
///
///格式为hh:mm的时间
///
公共字符串时间
{
获取{return String.Format(“{0:00}:{1:00}”,小时,分钟);}
设置
{
字符串[]spl=value.Split(':');
Hour=Int32.Parse(spl[0]);
Minutes=Int32.Parse(spl[1]);
}
}
公共重写字符串ToString()
{
返回时间;
}
}
也有比较运算符,但我省略了它们。(我认为它们不太重要) 看来您需要使用
CellStyle
格式,而不是重写ToString()
。但如果您仍然想重新发明轮子,请在时间内添加属性值,并绑定到它:
public class Time
{
public Time() { }
/// <summary>
/// the hour
/// </summary>
public int Hour
{
get;
set;
}
/// <summary>
/// the minuets
/// </summary>
public int Minutes
{
get;
set;
}
/// <summary>
/// the time in format hh:mm
/// </summary>
public string Value
{
get { return String.Format("{0:00}:{1:00}", Hour, Minutes); }
set
{
string[] spl = value.Split(':');
Hour = Int32.Parse(spl[0]);
Minutes = Int32.Parse(spl[1]);
}
}
}
为什么你没有使用TimeSpan
?@TimSchmelter三个原因-a。TimeSpan保存的数据比我需要的多,b。更容易自定义您自己编写的类,c。我想把我的手弄脏。所以,通过使用构造函数,你试图创建一个新的时间对象,而不是编辑现有的时间对象?您将要公开一个Set方法。@ChristoferOlsson我想类Time
中的where在哪里,但是如何公开呢?我有一个获取字符串的属性。我想运算符=会很好,但你不能在c#中重写它。史蒂夫B:难道不是重新发明了我们大家是如何开始的吗?重写ToString
很有用。另外,为什么不绑定到Time.Time
property?@elyashiv您可以随意命名它,直到您阅读到某人的代码,其属性以小写字母开头。当然,您可以保持ToString
override。
Text={Binding YourTimeProperty.Value, Mode=TwoWay}