I have three textboxes right now:
<TextBox Name="SDate1" Text="{Binding Source={x:Static System:DateTime.Now}, Mode=OneWay, StringFormat='MM/dd/yyyy'}" />
<TextBox Name="SDate2" />
<TextBox Name="STime1" Text="{Binding Source={x:Static System:DateTime.Now}, Mode=OneWay, StringFormat='hh:mm:ss'}" />
In the code behind:
SDate2.Text = String.Format("{0},{1}/{2}",
now.Year,
now.DayOfYear.ToString("d3"),
now.ToString("HHmmss"));
What this looks like:
What I would like to do is, if I edit any part of one textbox, it should edit the others as well at the appropriate part. So If I changed the 2016
part in the first text box to 2017
, the SDate2
like so:
This should also work if I change the hours/minutes/seconds in STime
which will change the last part of SDate2
and vice versa.
Changing the day in SDate1
will change the dayOfYear
in SDate2
and vice versa.
What would be the best way to achieve something like this?
Edit: I can bind the textboxes together, but the format isn't kept, and it's the same text in all the textboxes.
Edit 2: Here's the code behind in the xaml.cs file I tried.
public partial class TestDate : Window, INotifyPropertyChanged
{
private DateTime _dateInViewModel;
public TestDate()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
public DateTime DateInViewModel
{
get { return _dateInViewModel; }
set
{
_dateInViewModel = value;
OnPropertyChanged(new PropertyChangedEventArgs("DateInViewModel"));
}
}
}
Here's the update XAML for the textboxes:
<TextBox Name="SDate1" Text="{Binding DateInViewModel, StringFormat='MM/dd/yyyy'}" />
<TextBox Name="SDate2" Text="{Binding DateInViewModel}" />
<TextBox Name="STime1" Text="{Binding DateInViewModel, StringFormat='hh:mm:ss'}" />
The reason this is not working is because you are binding to separate
DateTime
instances. All threeTextBox
es should bind to the sameDateTime
instance. In a proper MVVM implementation you should have a viewmodel with aDateTime
property, lets call itDateInViewModel
:The viewmodel should implement the
INotifyPropertyChanged
interface, so the bindings are notified when the property is changing.Instead of setting
SDate2
'sText
to thatstring.Format(...)
you just setDateInViewModel
in the viewmodel:And finally your XAML:
You can change the bindings'
UpdateSourceTrigger
toPropertyChanged
to see instant updates as you edit. The defaultUpdateSourceTrigger
for theTextBox
'sText
binding isLostFocus
so other bindings are only notified when you click outside theTextBox
.