我在DataGrid中遇到DatePicker的问题。当我在单元格中第一次单击时,DatePicker会显示当前日期,但是当我单击下一个单元格时,DataGridTextColumn日期会更改为默认值01-01-0001。如何在DataGrid中的DatePicker中保留所选日期?
<!--------------------------------------xaml------------------------------------------->
<DataGridTemplateColumn Header="Data" Width="70">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataZdarzenia, StringFormat='dd-MM-yyyy', Converter={StaticResource DateConverter}}" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<DatePicker x:Name="datePicker" SelectedDate="{x:Static sys:DateTime.Now}" FirstDayOfWeek="Monday"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--------------------------------------xaml------------------------------------------->
答案 0 :(得分:0)
这是正确的方法
创建DataConverter类
public class DateConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DateTime date = (DateTime)value;
if (date != null && date.Year != 1)
{
return date;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return DateTime.MinValue;
DateTime val;
if (value.ToString() == " ")
return DateTime.MinValue;
if (DateTime.TryParse(value.ToString(), out val))
return val;
else
return DateTime.MinValue;
}
}
在XAML中为资源添加此代码
xmlns:l="clr-namespace:Progject.Control.Converter.WPF"
<UserControl.Resources>
<l:DateConverter x:Key="dateConverter"/>
</UserControl.Resources>
当你有一个datepiker时,在截面网格中插入这段代码:
<DataGridTemplateColumn SortMemberPath="StartDate" ClipboardContentBinding="{Binding StartDate}" Header="Start date" IsReadOnly="False">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding Path=StartDate,Mode=TwoWay,Converter={StaticResource dateConverter}}" VerticalAlignment="Center" HorizontalAlignment="Left">
</DatePicker>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=StartDate,Mode=TwoWay,StringFormat={}{0:dd/MM/yyyy},Converter={StaticResource dateConverter}}" VerticalAlignment="Center" HorizontalAlignment="Left">
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
答案 1 :(得分:-1)
你的绑定应该是TwoWay
<TextBlock Text="{Binding DataZdarzenia, Mode=TwoWay, StringFormat='dd-MM-yyyy', Converter={StaticResource DateConverter}}" HorizontalAlignment="Center"/>