简体   繁体   中英

ValidationError template in a custom textbox control

I´ve created a custom control extending the textbox control to allow only alphanumeric characters to be entered.

Afterwards, I have implemented error handling with INotifyDataErrorInfo. The problem is that when displaying errors, in the normal texbox it is displayed correctly, but in my custom textbox they are not shown, only the border turns red.

在此处输入图像描述

The custom textbox it's a little bit smaller and it's got like a double border.

This is my code:

// CustomTextbox.cs
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Windows.Input;

namespace ExampleApp.Controls
{
    public class CustomTextbox: TextBox
    {
        private static readonly Regex regex = new Regex("^[a-zA-Z0-9]+$");

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                e.Handled = true;
            }

            base.OnKeyDown(e);
        }

        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            if (!regex.IsMatch(e.Text))
            {
                e.Handled = true;
            }

            base.OnPreviewTextInput(e);
        }
    }
}
// MainWindow.xaml

<customControls:CustomTextbox Text="{Binding Title}"
    FontSize="32" Width="200"
    HorizontalAlignment="Center" 
    VerticalAlignment="Center" 
    Margin="0 -200 0 0"
/>
<TextBox Text="{Binding Title}"
    FontSize="32" Width="200"
    HorizontalAlignment="Center"
    VerticalAlignment="Center"
/>

Do I need to inherit a template or something similar from the Textbox?

Thanks!

<customControls:CustomTextbox Text="{Binding Title}"
    FontSize="32" Width="200"
    HorizontalAlignment="Center" 
    VerticalAlignment="Center" 
    Margin="0 -200 0 0"
    Style={StaticRessource {x:Type TextBox}}
/>

With this you will get the same style as the TextBox. This won't work, if you have set the TextBox style explicit. In this case you just need to copy the style property from the TextBox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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