I have a SQLite database table with multiple columns.
The model representing that looks something like this
public class Bills : ViewModelBase
{
private int _id;
public int Id
{
get
{
return _id;
}
set
{
SetValue(ref _id, value);
}
}
private string _billDt;
public string BillDt
{
get
{
return _billDt;
}
set
{
SetValue(ref _billDt, value);
}
}
private string _amt;
public string Amt
{
get
{
return _amt;
}
set
{
SetValue(ref _amt, value);
}
}
private string _dueDt;
public string DueDt
{
get
{
return _dueDt;
}
set
{
SetValue(ref _dueDt, value);
}
}
}
Now I've created a CRUD form for saving/editing data with some text boxes for some fields and Datepicker's for date fields like BillDt
, DueDt
etc.
The datepicker's XAML looks something like this
<DatePicker
FontSize="14"
SelectedDate="{Binding BillDt, BindingGroupName=Group1, UpdateSourceTrigger=PropertyChanged}"
Grid.Column="1"
Grid.Row="3"/>
I've also added some styling in app.xaml resources like
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="IsReadOnly" Value="True"/>
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox"
Text="{Binding Path=SelectedDate, StringFormat='dd-MM-yyyy',
RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
What I'm trying to do is when I save the data to my database the data of BillDt
, DueDt
should be saved in the format yyyy-MM-dd and when it is displayed in the Datepicker's it would show them in the format dd-MM-yyyy.
Currently the already stored data in the database table have the BillDt
, DueDt
values in the format yyyy-MM-dd and when I search them in my CRUD form they are shown in the desired format i.e. dd-MM-yyyy but when I make some changes using the Datepicker's and save it, the values are stored in the database tables in the format dd-MM-yyyy 00:00:00 instead of the desired format of yyyy-MM-dd.
How do I fix this ? Do I need to use some variation of IValueConverter or something like that ? How do I use it in my app?
CodePudding user response:
I think you can parse it in the getter, so when stored in db it will be in "yyyy-MM-dd" format
public string DueDt
{
get
{
var b = DateTime.TryParse(_dueDt, out DateTime dt);
return b ? dt.ToString("yyyy-MM-dd") : _dueDt;
}
set
{
SetValue(ref _dueDt, value);
}
}