WPF - DatePicker Masked输入

问题描述 投票:1回答:2

我正在开发一个WPF应用程序,我有两个日期选择输入,其中使用可以选择日期,但我有这些输入的一些问题导致用户可以在它上面写任何他们想要的东西,如下图所示

enter image description here

有没有办法掩盖这些输入?作为dd / mm / yyyy只允许用户写日期并自动插入/斜杠?

我尝试按照qazxsw poi但没有工作,因为它只在用户从日历中选择它之后格式化日期

我知道有一些“蒙面输入”,但它们不适用于datepicker输入

提前致谢。

编辑

这是我的xaml代码

this example
c# wpf xaml datepicker
2个回答
1
投票

在DatePicker中创建一个<Border Grid.Column="0" Grid.Row="1" Margin="10 0 0 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top"> <DatePicker x:Name="EDT_DATA_INICIAL"></DatePicker> </Border> <Border Grid.Column="1" Grid.Row="1" Margin="10 0 10 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top"> <DatePicker x:Name="EDT_DATA_FINAL"></DatePicker> </Border> 事件并处理其中的逻辑。以下示例将输入限制为数字和“/”。如果你想这样做,你必须弄清楚如何自己输入“/”。

也许循环遍历字符串的每个字符,并确定是否需要在某个点添加“/”。您可以PreviewTextInput阻止用户输入,然后根据需要设置e.Handled = true。这应该足以让你入门。

DatePicker.Text

正则表达式引用isprivate void DatePicker_PreviewTextInput(object sender, TextCompositionEventArgs e) { DatePicker dp = (DatePicker)sender; Regex regex = new Regex("[^0-9/]"); //regex that matches allowed text e.Handled = regex.IsMatch(e.Text); }


0
投票

只是补充@Tronald的回答我使用他的事件PreviewTextInput

我在keyUp事件中使用此代码补充它

System.Text.RegularExpressions

格式化仅使用数字或ex:18061993> 18/06/1993的日期,当日期不正确时,清除输入防止错误

private void SetDateFormat(object sender, KeyEventArgs e) { DatePicker dt = (DatePicker)sender; string justNumbers = new String(dt.Text.Where(Char.IsDigit).ToArray()); if (justNumbers.Length == 8) { string newDate = justNumbers.Insert(2, "/").Insert(5, "/"); try { dt.SelectedDate = DateTime.Parse(newDate); }catch(Exception ex) { dt.text = ""; } } }

© www.soinside.com 2019 - 2024. All rights reserved.