wpf c# 和日期选择器,如何更改格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14630318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:19:52  来源:igfitidea点击:

c# and date picker, how to change format?

c#wpfwpf-controlsdatepicker

提问by álvaro García

I have a datepicker in my C# 4.0 (WPF) application and I would like to change the format of the date that is visible in the textBox to yyyy/MM/dd. Now I see the format dd/MM/yyyy.

我的 C# 4.0 (WPF) 应用程序中有一个日期选择器,我想将文本框中可见的日期格式更改为 yyyy/MM/dd。现在我看到格式为 dd/MM/yyyy。

In my axml of the datePicker I have this code:

在 datePicker 的 axml 中,我有以下代码:

<DatePicker Height="25" HorizontalAlignment="Left" Margin="5,36,0,0" Name="dtpStartDate"
                    SelectedDate="{Binding StartDateSelectedDate}" VerticalAlignment="Top" Width="115">
            <DatePicker.Resources>
                <Style TargetType="{x:Type DatePickerTextBox}">
                    <Setter Property="Control.Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <TextBox x:Name="PART_TextBox" 
                                    Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, StringFormat={}{0:yyyy/MM/dd}}" />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DatePicker.Resources>
        </DatePicker>

This seems in a first time that all works fine, I can see the date in the format that I want, and I can change the date manually or using the calendar, and in both ways the date that arrives to the viewModel is the correct.

这似乎是第一次一切正常,我可以看到我想要的格式的日期,我可以手动或使用日历更改日期,并且在这两种方式中到达 viewModel 的日期都是正确的。

But I have a problem, because I would like to detect that if the date is empty, in my view model control this case. But If I clear the datepicker, in my view model arrives the last correct date, so I can't check if the date is empty or not.

但是我有一个问题,因为我想检测日期是否为空,在我的视图模型中控制这种情况。但是如果我清除日期选择器,在我的视图模型中会到达最后一个正确的日期,所以我无法检查日期是否为空。

So how can I modify the format of the date in the date picker and control if the date is empty/null or not?

那么如何修改日期选择器中的日期格式并控制日期是否为空/空?

Thanks. Daimroc.

谢谢。戴姆洛克。

回答by Claude Catonio

you can try the following solution.

您可以尝试以下解决方案。

First create the following converter :

首先创建以下转换器:

public class StringToDateTimeConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return null;
        }
        return ((DateTime)value).ToString(parameter as string, CultureInfo.InvariantCulture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (string.IsNullOrEmpty(value as string))
        {
            return null;
        }
        try
        {
            DateTime dt = DateTime.ParseExact(value as string, parameter as string, CultureInfo.InvariantCulture);
            return dt as DateTime?;
        }
        catch (Exception)
        {
            return null;
        }
    }
}

Then in the xaml, you will have to create an instance of the converter and use it in the textbox of the DatePicker

然后在 xaml 中,您必须创建转换器的实例并在 DatePicker 的文本框中使用它

<Window x:Class="TestDatePicker.MainWindow"
    ... 
    xmlns:converters="clr-namespace:TestDatePicker"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    ...
    <converters:StringToDateTimeConverter x:Key="StringToDateTimeConverter" />
</Window.Resources>
<Grid DataContext="{StaticResource MainWindowVM}">
    ...
    <DatePicker Height="25" HorizontalAlignment="Left" Margin="5,36,0,0" Name="dtpStartDate"
                SelectedDate="{Binding StartDateSelectedDate}" VerticalAlignment="Top" Width="115">
        <DatePicker.Resources>
            <Style TargetType="{x:Type DatePickerTextBox}">
                <Setter Property="Control.Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <TextBox x:Name="PART_TextBox" 
                                Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, Converter={StaticResource StringToDateTimeConverter}, ConverterParameter=yyyy/MM/dd}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </DatePicker.Resources>
    </DatePicker>
    ...
</Grid>

Finally, in the viewmodel, the property must be of type DateTime? (i.e a nullable DateTime).

最后,在视图模型中,属性必须是 DateTime 类型吗?(即一个可为空的 DateTime)。

    private DateTime? _startDateSelectedDate;
    public DateTime? StartDateSelectedDate
    {
        get { return _startDateSelectedDate; }
        set
        {
            if (_startDateSelectedDate != value)
            {
                _startDateSelectedDate = value;
                RaisePropertyChanged(() => this.StartDateSelectedDate);
            }
        }
    }

I hope this will help you

我希望这能帮到您

Regards

问候

Claude

克劳德

回答by Sukram

defaultly the DateTimerPicker does not support null values.

默认情况下 DateTimerPicker 不支持空值。

Maybe this postfrom MSDN with the same topic can help you.

也许这篇来自 MSDN 的相同主题的帖子可以帮助你。

There you will find other ideas how to implement it or some code project for nullable date time picker.

在那里你会发现其他想法如何实现它或一些可空日期时间选择器的代码项目。