我尝试了下面的代码,但没有正常工作。使用wpf使用屏蔽文本框textchanged两次计算总时间。请帮帮我
xaml page:
<msk:MaskedTextBox Grid.Row="0" Grid.Column="3" Margin="5,5,5,5" Height="30" Text="{Binding Path=FromTime}" Name="txt_starttime" Mask="00:00" HorizontalAlignment="Center" VerticalAlignment="Center" TextChanged="txt_totalhours_TextChanged" />
<msk:MaskedTextBox Grid.Row="0" Grid.Column="4" Margin="5,5,5,5" Height="30" Text="{Binding Path=ToTime}" Name="txt_endtime" Mask="00:00" HorizontalAlignment="Center" VerticalAlignment="Center" TextChanged="txt_totalhours_TextChanged"/>
<TextBox Grid.Row="0" Grid.Column="5" Margin="5,5,5,5" Text="{Binding Path=TotalHours}" Name="txt_totalhours" TextChanged="txt_totalhours_TextChanged"/>
代码背后的代码:
private void txt_totalhours_TextChanged(object sender, TextChangedEventArgs e)
{
if (null == txt_totalhours || null == txt_starttime || null == txt_endtime)
return;
//if (lb_weekDays.SelectedItems.Count > 0)
//{
string StartTimeText = txt_starttime.Text;
string EndTimeText = txt_endtime.Text;
string[] Startparts = StartTimeText.Split(':');
string[] Endparts = EndTimeText.Split(':');
var resultStartHour = Int32.MinValue;
var isIntstarttimeHour = Int32.TryParse(Startparts[0], out resultStartHour);
var resultEndHour = Int32.MinValue;
var isIntendtimeHour = Int32.TryParse(Endparts[0], out resultEndHour);
var resultHour = isIntstarttimeHour ? ((isIntendtimeHour ? (resultEndHour - resultStartHour) : resultStartHour)) : (isIntendtimeHour ? resultEndHour : 0);
int resHour = resultHour;
var resultStartMin = Int32.MinValue;
var isIntstarttimeMin = Int32.TryParse(Startparts[1], out resultStartMin);
var resultEndMin = Int32.MinValue;
var isIntendtimeMin = Int32.TryParse(Endparts[1], out resultEndMin);
var resultMin = isIntstarttimeMin ? ((isIntendtimeMin ? (resultEndMin - resultStartMin) : resultStartMin)) : (isIntendtimeMin ? resultEndMin : 0);
int resMin = resultMin;
int lbCount = lb_weekDays.SelectedItems.Count;
int ab = 0, abc = 0;
ab = resHour * lbCount;
abc = resMin * lbCount;
if (abc > 59)
{
int quotient = 0;
quotient = abc / 60;
ab = ab + quotient;
int remainder = 0;
remainder = abc % 60;
abc = remainder;
}
txt_totalhours.Text = ab + ":" + abc;
//}
//else
//{
// MessageBox.Show("Please Select WeekDays Before Enter Time");
//}
}
答案 0 :(得分:1)
您应该使用TimeSpan为您做繁重的工作。使用开始和结束时间创建两个DateTime变量,并使用生成的TimeSpan从较晚的时间减去较早的时间,以获得两者之间的总小时数。
var dt1 = DateTime.Now.AddHours(-2);
var dt2 = DateTime.Now.AddHours(1.55);
var total = (dt2 - dt1).TotalHours;