Reputation: 1092
How can I bind (TwoWay) a DateTime to a TextBox such that only the Year of the DateTime is displayed and the TextBox accepts input as a Year as well (i.e. User can type "2014" and this will bind successfully to the DateTime)?
I have the following:
TextBox Margin="10, 1" MinWidth="100" Text="{Binding LastGoodDate, StringFormat={}{0:yyyy}}" >
Which successfully shows the DateTime in yyyy format, however the binding fails when the user types "2014".
I can get around this by binding instead to an intermediate string property, and then manually parsing the result and storing it in the DateTime, but I would like to avoid this if possible.
Any ideas?
Upvotes: 2
Views: 1462
Reputation: 102753
It's probably easiest to do this in the view-model, by adding a separate "Year" property. Eg:
TextBox Text="{Binding LastGoodYear}" >
The property should not have its own backing field, but should modify the date as needed:
public int LastGoodYear
{
get
{
return LastGoodDate.Year;
}
set
{
LastGoodDate = new DateTime(value, LastGoodDate.Month, LastGoodDate.Day);
}
}
Also make sure to trigger "PropertyChanged" (LastGoodYear) in the "LastGoodDate" setter.
Upvotes: 3