DataGrid DateTime IValueConverter,仅编辑时间,保留日期

时间:2019-03-01 09:03:27

标签: c# wpf xaml datetime ivalueconverter

我想在两列中分别显示DateTime作为Date和Time。使用输入“ HHmmss”更新时间列会更新时间,但会将日期重置为当前日期。如何保存日期?

public class TimeToStringConverter : IValueConverter
{
    public string Format { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Format = "HH:mm:ss";
        DateTime DateTimeValue = (DateTime)value;
        return DateTimeValue.ToString(Format);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string strValue = value.ToString();
        DateTime DateTimeValue;
        string format = "HHmmss";
        if (value.ToString().Length == 4)
            format = "HHmm";
        var res1 = DateTime.TryParseExact(strValue, format, null, DateTimeStyles.None, out DateTimeValue);
        if (res1)
            return DateTimeValue;
        return value;
    }
}

xaml:

<UserControl.Resources> 
    <valrule:TimeToStringConverter x:Key="timeConverter"/>
</UserControl.Resources>


<DataGridTextColumn Header="Time" MinWidth="50">
    <DataGridTextColumn.Binding>
        <Binding Path="Time" StringFormat="HH:mm:ss" UpdateSourceTrigger="Default"
                Converter="{StaticResource timeConverter}"  >
            <Binding.ValidationRules>
                <valrule:DateValidation/>
            </Binding.ValidationRules>
        </Binding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

1 个答案:

答案 0 :(得分:0)

如果您不想像@Nawed Nabi Zada所说的那样将时间和日期分成两个属性,那么我还有另一种解决方案,它有点怪异。 您可以将原始日期保存在转换器中。请注意,这仅在仅在一个地方使用转换器的情况下有效。

public class TimeToStringConverter : IValueConverter
{
    private DateTime _originaldate;
    public string Format { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Format = "HH:mm:ss";
        DateTime DateTimeValue = (DateTime)value;
        _originaldate = (DateTime)value;
        return DateTimeValue.ToString(Format);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string strValue = value.ToString();
        DateTime DateTimeValue;
        string format = "HH:mm:ss";
        if (value.ToString().Length == 4) format = "HH:mm";
        var res1 = DateTime.TryParseExact(strValue, format, null, DateTimeStyles.None, out DateTimeValue);
        if (res1)
        {
            DateTimeValue = _originaldate.Date + DateTimeValue.TimeOfDay;
            return DateTimeValue;
        }
        return value;
    }
}