Search code examples
wpfdatetimehourminute

WPF Edit hours and minutes of a DateTime


I have 3 TextBoxes to edit a DateTime. What is important to notice is that those 2 TextBoxes are editing the hour and minutes of the first TextBox DateTime value. One to edit the Date and 2 to edit hour and minutes. How would you do that? The code below doesn't reflect the DateTime changes when editing the hour or minute, because it does ToString("HH") and the DateTime value is lost:

 <TextBox Text="{Binding MyDateTime}"  />

    <!--This cannot work : it's just for clearing purposes -->
    <TextBox Text="{Binding MyDateTime, StringFormat=\{0:HH\}}}"  />
    <TextBox Text="{Binding MyDateTime}, StringFormat=\{0:mm\}}"  />

Of course I can have a ViewModel as DataContext where I would solve it programmatically. But I just want to know if there is any possiblity directly in XAML


Solution

  • It is not easily possible with XAML only. There are several possibilities how to solve this:

    1. Write custom control or user control that can do this

    You could wirte a custom control / user control (e.g. DateTimeTextBox) that has a Property DateTime Value that your xaml can bind against and that contains logic to convert to the datetime value entered in one of its two textboxes. Instead of two textboxes you could also have something like maskedtextbox.

    2. Two dedicated properties in the ViewModel

    If you go with MVVM you could give your ViewModel two dedicated properties int DateTimeHours int DateTimeMinutes and bind against that:

    <TextBox Text="{Binding MyDateTimeHours}"  />
    <TextBox Text="{Binding MyDateTimeMinutes}"  />
    

    Your ViewModel would then merge the two properties to a single DateTime value.