简体   繁体   English

如何获得DatePicker仅接受WPF中的数字输入?

[英]How do I get a DatePicker to only accept numeric input in WPF?

I have the following DatePicker control: 我有以下DatePicker控件:

<Grid x:Name="LayoutRoot" Background="White">
       <DatePicker Margin="2" Grid.Column="1" VerticalAlignment="Center"/>
</Grid>

Is it possible to allow user only to set numeric input? 是否可以只允许用户设置数字输入? Or how to disable the Textbox input in case it's not possible to acheive 或在无法实现的情况下如何禁用文本框输入

Try this one: 试试这个:

 <DatePicker Margin="2" Grid.Column="1" VerticalAlignment="Center">
            <DatePicker.Resources>
                <Style TargetType="DatePickerTextBox">
                    <Setter Property="IsReadOnly" Value="True"/>
                </Style>
            </DatePicker.Resources>
        </DatePicker>
</Grid>

This code only allows to enter numeric values in DatePicker 此代码仅允许在DatePicker中输入数字值

XAML: XAML:

<DatePicker Margin="2" Grid.Column="1"
            PreviewTextInput="phoneNumber_PreviewTextInput" 
            VerticalAlignment="Center"/>

Code behind 后面的代码

private void phoneNumber_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    char character = Convert.ToChar(e.Text);
    if (char.IsNumber(character))
    {
        e.Handled = false;
    }
    else
    {
        e.Handled = true;
    }
}

Actually I appreciate your answers and I really enjoy them but I would like the solution I found, in fact I used the Regex and below is the used code : 实际上,我很感谢您的回答,也非常满意,但是我希望我找到的解决方案,实际上我使用了Regex ,下面是使用的代码:

private bool IsTextAllowed(string text)
{
     Regex regex = new Regex("[^0-9/]+"); 
     return !regex.IsMatch(text);
}

private void DatePicker_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
     e.Handled = !IsTextAllowed(e.Text);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM