Paulo Hortelan
Paulo Hortelan

Reputation: 15

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

I'm building a project using WPF with Material Design in XAML. The objetive is to do a valiation or a mask for a textbox. I can't use other extensions that provides a Mask in Textbox because the Style will be different from the Material Design TextBox.

Simple example of code:

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

What needs to be done: a mask for a validation like 00000-000 (accepting values like 12345-789). What is the best way to do it?

Upvotes: 1

Views: 6365

Answers (1)

user3188639
user3188639

Reputation:

You can use existing masked textbox and overwrite the style to match your style, or write/copy your own.

This https://github.com/xceedsoftware/wpftoolkit/wiki/MaskedTextBox works quite nice and it's not hard to redefine the style. You can also look at the source https://github.com/xceedsoftware/wpftoolkit/blob/master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit/MaskedTextBox/Implementation/MaskedTextBox.cs and try to implement your own.

However, it's the wrong way to go, because restyling controls is one of WPF strengths.

EDIT: Simple example

To redefine style in a single view, try something like this:

<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>

To redefine style everywhere, create a global resource dictionary (for example, in directory Themes/Generic.xaml). Add something like this:

<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>

and reference this dictionary in App.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Themes/Generic.xaml" />
        </ResourceDictionary.MergedDictionaries>

If you already have a style for a TextBox, you can just apply this style to the MaskedTextBox

Upvotes: 1

Related Questions