c# - 自定义文本框控件中的 ValidationError 模板
问题描述
我创建了一个自定义控件,扩展了文本框控件,只允许输入字母数字字符。
之后,我使用 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"
/>
我是否需要从文本框继承模板或类似的东西?
谢谢!
解决方案
<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 复制样式属性
推荐阅读
- angular - 如何为 templateUrl 和 styleUrls 使用绝对路径?- 角 6
- google-bigquery - Java.lang.RuntimeException:[Simba][JDBC](10220) 驱动程序不支持 BigQuery Talend 中的此可选功能
- python - Python - 如何在使用 json 更改数字(in-json)时打印出名称
- c# - 无法插入图像 CKEditor(解耦编辑器),即使在 ckfinder 中提供 uploadUrl 后也会出错
- android - NativeScript android NotificationChannel 错误
- python - Python 类不断互相调用
- powershell - 未输出哈希表数组
- c++ - 'std::is_convertible
::value':依赖名称不是类型;和错误 C2059:语法错误:'...' - jquery - jQuery DataTable 按钮在添加表格行时不显示
- javascript - 检测阵列变化的最佳方法是什么?