2017-10-13 52 views
0

我需要時間下表(「dd.MM.yyy」)和時間結合起來,並插入到一個DateTime對象:如何結合日期和時間WPF

例: 日期13/10/2017和TIME :10:30 - >聯合收割機日期結果:13/10/2017 10:30

XAML:

 //DATE ("dd.MM.yyy") 
    <DatePicker HorizontalAlignment="Center" 
     Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}"   
     SelectedDate="{Binding DeliveryDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged ,NotifyOnValidationError=True ,TargetNullValue=''}"/> 


     //TIME 
    <TextBox Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" > 
       <TextBox.Text > 
        <Binding Path="Time" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True" Mode="TwoWay" > 
         <Binding.ValidationRules> 
          <local:DateTimeValidationRule ValidationStep="RawProposedValue"/> 
         </Binding.ValidationRules> 
        </Binding> 
       </TextBox.Text> 
      </TextBox> 

視圖模型:

public DateTime DeliveryDate; 
    private TimeSpan time; 
    public TimeSpan Time 
    { 
     get { return time; } 
     set 
     { 
      time = value; 
      OnPropertyChanged("Time"); 
     } 
    } 


    public DateViewModel() 
    { saveDate = new RelayCommand<string>(SaveDateFunction); 
     DeliveryDate = DateTime.Now.Date ; 

     } 

    public void SaveDateFunction(string obj)   
    { 
     DateTime combined = DeliveryDate.Add(Time); 
    } 

我有錯誤結果:13/10/2017 00:00:00 我該如何解決它?

回答

0

嘗試以下簽名的SaveDateFunction方法

public void SaveDateFunction(string obj)   
{ 
    DateTime combined = DeliveryDate.AddMilliseconds(Time.TotalMilliseconds); 
} 

可以嘗試的工作例如here

DateTime d=DateTime.Now.Date; 
TimeSpan t = DateTime.Now.TimeOfDay; 
DateTime combined = d.AddMilliseconds(t.TotalMilliseconds); 
+0

非常感謝,它的工作原理:) – TunNet

0

時間未設置,但您沒有得到NullReferenceException,因爲TimeSpan是一種結構並且具有默認值而不是null

由於您需要轉換器,因此未從UI向您的媒體資源傳遞值。我相信你可以在輸出窗口中看到錯誤。

public class StringToTimeSpanConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     //Your code here 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

DeliveryDate是一個字段,而不是屬性,所以它的綁定不起作用。

相關問題