如何在 WPF 中的文本框上使用 mask/validation?

How to use a mask/validation on textbox in WPF?

我正在 XAML 中使用 WPF 和 Material Design 构建一个项目。目标是为文本框做一个验证或掩码。我无法使用在文本框中提供掩码的其他扩展,因为样式将不同于 Material 设计文本框。

简单的代码示例:

<TextBox x:Name="CEPTextBox" Style="{StaticResource MaterialDesignTextBox}" HorizontalAlignment="Stretch" VerticalAlignment="Top">

需要做什么:用于验证的掩码,如 00000-000(接受 12345-789 等值)。最好的方法是什么?

您可以使用现有的蒙版文本框并覆盖样式以匹配您的样式,或者write/copy您自己的样式。

这个 https://github.com/xceedsoftware/wpftoolkit/wiki/MaskedTextBox 效果很好,重新定义风格并不难。 也可以看看源码 https://github.com/xceedsoftware/wpftoolkit/blob/master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit/MaskedTextBox/Implementation/MaskedTextBox.cs 并尝试实现你自己的。

但是,这是错误的方法,因为重新设计控件样式是 WPF 的优势之一。

编辑:简单示例

要在单个视图中重新定义样式,请尝试这样的操作:

<UserControl x:Class="PA.Views.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        >
<UserControl.Resources>
<Style TargetType="{x:Type xctk:MaskedTextBox}">
    <Setter Property="Background" Value="LightGreen"/>
    <Setter Property="Foreground" Value="DarkRed"/>
</Style>    
</UserControl.Resources>
   
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <xctk:MaskedTextBox />
</Grid>

要在所有地方重新定义样式,请创建全局资源字典(例如,在目录 Themes/Generic.xaml 中)。添加如下内容:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
                >

<Style TargetType="{x:Type xctk:MaskedTextBox}">
    <Setter Property="Background" Value="LightGreen"/>
    <Setter Property="Foreground" Value="DarkRed"/>
</Style>

并在 App.xaml

中引用该词典
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Themes/Generic.xaml" />
        </ResourceDictionary.MergedDictionaries>

如果您已经有了 TextBox 的样式,您可以将此样式应用到 MaskedTextBox