0

我创建了一个自定义控件,扩展了文本框控件,只允许输入字母数字字符。

之后,我使用 INotifyDataErrorInfo 实现了错误处理。问题是当显示错误时,在正常的texbox中它显示正确,但在我的自定义文本框中它们没有显示,只有边框变成红色。

在此处输入图像描述

自定义文本框有点小,它就像一个双边框。

这是我的代码:

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

我是否需要从文本框继承模板或类似的东西?

谢谢!

4

1 回答 1

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

这样,您将获得与 TextBox 相同的样式。如果您明确设置了 TextBox 样式,这将不起作用。在这种情况下,您只需要从 TextBox 复制样式属性

于 2020-06-04T16:54:29.487 回答