【问题标题】:wpf mvvm datepicker textbox auto formatwpf mvvm datepicker 文本框自动格式
【发布时间】:2013-08-21 21:16:06
【问题描述】:

是否可以在日期选择器的文本框中自动格式化用户输入日期?

我有以下代码

<Style TargetType="{x:Type DatePicker}">
    <Setter Property="Foreground" Value="{DynamicResource TextBrush}"/>
    <Setter Property="IsTodayHighlighted" Value="True"/>
    <Setter Property="SelectedDateFormat" Value="Short"/>
    <Setter Property="Padding" Value="2"/>
    <Setter Property="CalendarStyle" Value="{DynamicResource DatePickerCalendarStyle}" />
</Style>

<Style TargetType="{x:Type DatePickerTextBox}">
    <Setter Property="Foreground" Value="{DynamicResource TextBrush}"/>
    <Setter Property="Padding" Value="2"/>
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <TextBox x:Name="PART_TextBox"
 Text="{Binding Path=SelectedDate, StringFormat='dd/MM/yyyy', 
 RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

在我看来我有

<DatePicker Height="25" HorizontalAlignment="Left" Margin="518,34,0,0" Name="DateThru" VerticalAlignment="Top" Width="115" SelectedDate="{Binding DateThruSelected, Mode=TwoWay}" IsEnabled="{Binding DateThruIsEnabled}" >
</DatePicker>

所以有两个问题。 第一的 当我输入文本框“030613”或“03062013”​​并点击时,我希望它会在 datpicker 的文本框中自动格式化为“03/06/2013”​​。

其次,我期望 SelectedDate 属性设置为“03/06/2013”​​。 (如果我从嵌入式日历中选择一个日期,则 SelectedDate 绑定工作正常。)

我在此处发布的当前代码两者都没有。 知道如何实现这两个目标吗?

提前致谢!

【问题讨论】:

    标签: wpf c#-4.0 mvvm


    【解决方案1】:

    关于第一期:

    我想到了正则表达式。为了方便使用,尝试使用一些抽象类,并派生它,例如:

    public abstract class DateTimeRegexPattern
    {
        public abstract DateTime DateTime { get; }
    
        public abstract bool IsMatch(string input);
    }
    

    对于您希望它被识别的每个模式,您派生该抽象类(可以增强),并将它们放在一个列表中。每当文本框的内容发生变化时,为了检测可以应用哪种模式,请使用 LINQ。

    List<DateTimeRegexPattern> patterns = new List<DateTimeRegexPattern>();
    // Fill the list with one instance of each of derived classes of DateTimeRegexPattern
    DateTimeRegexPattern matching = patterns.FirstOrDefault(x => x.IsMatch("030613"));
    

    然后,如果有任何模式匹配,则检索 DateTime,并将其应用于 DatePicker,如果当前日期不同。

    关于第二期: http://msdn.microsoft.com/fr-fr/library/system.windows.controls.datepicker.selecteddatechanged.aspx 这个事件应该可以解决问题。当日期更改时,更改文本框的内容,如果日期不同。

    【讨论】:

    • 嗨,大卫,感谢您的回复。当我尝试在文本框中格式化输入的日期时,我无法访问嵌入在 DatePicker 中的 DatePickerTextBox。所以我的第一个问题变成了如何访问嵌入在 DatePicker 中的 DatePickerTextBox。
    • 既然你有两个类的实例,一定有一些地方(共同的父母)可以看到它们。从那里进行所需的初始化?
    • 我通过从事件处理程序中的 routedeventargs 获取 texbox 来解决它。感谢您的帮助。
    猜你喜欢
    • 2011-05-02
    • 2022-01-18
    • 2012-11-24
    • 2015-04-21
    • 2015-10-16
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多