views:

232

answers:

2

Hi !

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

A: 

You will need to use a converter with 2way binding and a converter parameter. Save the original hour in the Converter. Then you can update the binding source appropriately.

Snake
Well.. if it's true, I'd like to see an example of that converter. ConverteBack: You only have a string value (let's say "16"), how would you get the whole Date from it ?
PaN1C_Showt1Me
This is not going to work, because you do not have any acess to current DateTime value (as a whole) and hence you can not merge the hours/minutes with it. You also not save any state in a converter because the same instance can be used used multiple times.
bitbonk
Create a user control with the textbox in it and save it like that?
Snake
+1  A: 

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.

bitbonk
Let's talk about 3.: Well the problem is that I cannot merge it with the actual DateTime, because those hours and minutes are part of the first DateTime ! So I need to provide the recent DateTime to the ConvertBack method.
PaN1C_Showt1Me
Yes you are right this is not easily possible. I deleted that idea
bitbonk
Yep.. u know.. it seems to me like some problems cannot be overcome without MVVM.
PaN1C_Showt1Me
MVVM makes a lot of things easier. One must just not fall into the pit of going all tunnel visioned on MVVM.
bitbonk