あなたはConvertBack
法上の例外を取得している:だから、
Exception thrown: 'System.FormatException' in mscorlib.dll
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
Exception thrown: 'System.FormatException' in mscorlib.dll
System.Windows.Data Error: 7 : ConvertBack cannot convert value '14/09/2016' (type 'String'). BindingExpression:Path=SelectedDate; DataItem='DatePicker' (Name='DateGviya'); target element is 'TextBox' (Name='PART_TextBox'); target property is 'Text' (type 'String') FormatException:'System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.Convert.ToDateTime(String value, IFormatProvider provider)
at System.String.System.IConvertible.ToDateTime(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'
カスタムコンバータを提供
public class MyCustomDateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
return ((DateTime)value).ToString("dd/MM/yyyy hh:mm:ss tt", culture);
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DateTime.ParseExact((string)value, "dd/MM/yyyy hh:mm:ss tt", culture);
}
}
XAML:
問題を解決します
<Window x:Class="WpfApplication293.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication293"
mc:Ignorable="d"
Title="Window1" Height="350" Width="350">
<Window.Resources>
<local:MyCustomDateConverter x:Key="Converter1" />
</Window.Resources>
<Window.DataContext>
<local:MyViewModel/>
</Window.DataContext>
<Grid>
<DatePicker x:Name="DateGviya" SelectedDate="{Binding CurrentDate}" HorizontalAlignment="Center" VerticalAlignment="Top">
<DatePicker.Resources>
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, StringFormat='dd/MM/yyyy hh:mm:ss tt', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, Converter={StaticResource Converter1}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DatePicker.Resources>
</DatePicker>
</Grid>
![enter image description here](https://i.stack.imgur.com/KJ5x9.gif)