使用DateTime信息填充ConverterParameter

时间:2013-12-17 09:25:47

标签: c# wpf datepicker

我正在尝试将DatePicker.DisplayDate绑定到TextBox.Text属性。绑定应该工作两天,应该显示和/或更改当前月份。意味着当我在TextBox中输入另一个月名时,DatePicker应该遵循。但是,DatePicker只应更改其月份。

例如,如果DatePicker已打开并且当前显示为18. 2018年2月,我在TextBox“12月”中输入,则DatePicker应更改为18. 2018年12月。

这是代码:

<Window.Resources>
    <converters:DateTimeToStringConverter x:Key="dateTimeToStringConverter"/>
</Window.Resources>
<StackPanel>
    <TextBox Text="{Binding ElementName=datePicker, Path=DisplayDate, Converter={StaticResource dateTimeToStringConverter}, StringFormat={}{0:D}}"/>
    <DatePicker x:Name="datePicker"/>
</StackPanel>

这是转换器:

public class DateTimeToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetMonthName(((DateTime)value).Month);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // how to just change month of datepicker but let day and year stay?
        return value;
    }
}

我想我可能需要使用ConverterParameter以某种方式检索有关DatePicker当前日期和年份的信息。这个月来自TextBox。

任何想法的人?

1 个答案:

答案 0 :(得分:1)

按如下方式使用XAML

  <StackPanel>
        <TextBox 
            Text="{Binding ElementName=datePicker, Path=DisplayDate, Converter={StaticResource dateTimeToStringConverter}, StringFormat={}{0:MMMM}}"/>
        <DatePicker x:Name="datePicker"/>
    </StackPanel>

和转换器如下:

public class DateTimeToStringConverter : IValueConverter
{
    private DateTime currentDisplayDate;
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        currentDisplayDate = (DateTime)value;
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
       bool flag;
            DateTime output;
            flag = DateTime.TryParseExact(currentDisplayDate.Day + " " + value.ToString().Trim() + " " + currentDisplayDate.Year, "d MMMM yyyy",
                                            CultureInfo.InvariantCulture,DateTimeStyles.None,out output);

        /* To handle month last day difference */
           if(!flag)
            flag = DateTime.TryParseExact(1 + " " + value.ToString().Trim() + " " + currentDisplayDate.Year, "d MMMM yyyy",
                                            CultureInfo.InvariantCulture, DateTimeStyles.None, out output);
       return flag ? output : currentDisplayDate;  

    }
}