自定义文本框控件中的ValidationError模板。

问题描述 投票:0回答:1

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

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

enter image description here

自定义文本框小了一点,而且有一个双边框。

这是我的代码。

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

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

谢谢!我创建了一个自定义控件,扩展了一个文本框。

c# wpf inheritance textbox inotifydataerrorinfo
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中复制样式属性。

© www.soinside.com 2019 - 2024. All rights reserved.