如何将时间值从Page.cs传递至ViewModel?
解决方案:传递"14h:15m"格式时间到ViewModel
1. 修复ViewModel的属性命名冲突
你的ViewModel里同时定义了DateTime和int类型的StartTime,会导致编译错误,先把int类型属性重命名以避免冲突:
public DateTime StartTime { get; set; } = DateTime.Today; public DateTime EndTime { get; set; } public int Duration { get; set; } private TimeSpan[] _StartTimeValues { get; set; } private int _StartTimeIndex = -1; // 重命名为SelectedStartTimeIndex,避免与DateTime类型的StartTime冲突 public int SelectedStartTimeIndex { get { return _StartTimeIndex; } set { _StartTimeIndex = value; if (value >= 0 && _StartTimeValues != null && value < _StartTimeValues.Length) { StartTime = DateTime.Today.Add(_StartTimeValues[value]); EndTime = StartTime.AddMinutes(Duration); } OnPropertyChanged(nameof(StartTime)); OnPropertyChanged(nameof(EndTime)); } }
2. 在Page.cs中解析"14h:15m"格式字符串
直接用int.Parse无法解析该格式,需要拆分字符串提取小时和分钟,再转换为TimeSpan或DateTime:
方法一:直接解析为DateTime赋值给ViewModel
string timevalue = "14h:15m"; // 拆分字符串提取小时和分钟 var parts = timevalue.Split(new[] { 'h', ':' }, StringSplitOptions.RemoveEmptyEntries); int hours = int.Parse(parts[0]); int minutes = int.Parse(parts[1]); // 组合为当日的DateTime对象赋值 _model.StartTime = DateTime.Today.AddHours(hours).AddMinutes(minutes);
方法二:匹配_StartTimeValues数组的索引赋值
如果需要通过索引关联数组中的TimeSpan元素,可先匹配对应索引再赋值:
string timevalue = "14h:15m"; var parts = timevalue.Split(new[] { 'h', ':' }, StringSplitOptions.RemoveEmptyEntries); int hours = int.Parse(parts[0]); int minutes = int.Parse(parts[1]); TimeSpan targetTime = new TimeSpan(hours, minutes, 0); // 找到数组中匹配的索引 int index = Array.IndexOf(_model._StartTimeValues, targetTime); if (index >= 0) { _model.SelectedStartTimeIndex = index; }
3. 异常处理建议
为避免输入格式错误导致崩溃,解析时增加校验:
int hours = 0; int minutes = 0; var parts = timevalue.Split(new[] { 'h', ':' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2 && int.TryParse(parts[0], out hours) && int.TryParse(parts[1], out minutes)) { // 解析成功,执行赋值逻辑 } else { // 处理格式错误,比如设置默认值 _model.StartTime = DateTime.Today; }
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

