使用MVVM CommunityToolkit实现控件UI验证错误可视化的问题
使用CommunityToolkit ObservableValidator实现WPF UI验证的正确姿势
你遗漏了UI层面的验证错误可视化配置——ObservableValidator只负责提供验证逻辑和错误通知(通过INotifyDataErrorInfo接口),WPF默认不会自动为绑定控件渲染错误高亮或消息,需要手动配置UI模板。
核心修改步骤:
移除ViewModel中多余的特性
ObservableValidator本身已经实现了INotifyDataErrorInfo接口,无需额外添加[NotifyDataErrorInfo]特性,删掉即可:public sealed partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); root.DataContext = new ViewModel(); } } public partial class ViewModel : ObservableValidator { [ObservableProperty] [Required(ErrorMessage = "Username cannot be empty.")] [MinLength(2, ErrorMessage = "Provide more than 1 Character.")] private string _name; }配置TextBox的验证绑定与错误模板
在XAML中,为TextBox指定验证错误的显示样式,同时明确声明绑定监听错误通知:<Grid x:Name="root"> <TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" Height="70" Width="150"> <!-- 定义验证错误时的控件外观 --> <Validation.ErrorTemplate> <ControlTemplate> <DockPanel> <!-- 红色边框包裹原控件 --> <Border BorderBrush="Red" BorderThickness="2"> <AdornedElementPlaceholder/> </Border> <!-- 右侧显示错误文本 --> <TextBlock Foreground="Red" Margin="5,0" Text="{Binding [0].ErrorContent}"/> </DockPanel> </ControlTemplate> </Validation.ErrorTemplate> <!-- 鼠标悬停显示错误消息 --> <TextBox.ToolTip> <Binding Path="(Validation.Errors)[0].ErrorContent" RelativeSource="{RelativeSource Self}"/> </TextBox.ToolTip> </TextBox> </Grid>(可选)全局统一验证样式
如果希望所有TextBox自动应用错误样式,可在App.xaml中定义全局Style,避免重复代码:<Application.Resources> <Style TargetType="TextBox"> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <DockPanel> <Border BorderBrush="Red" BorderThickness="2"> <AdornedElementPlaceholder/> </Border> <TextBlock Foreground="Red" Margin="5,0" Text="{Binding [0].ErrorContent}"/> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="Validation.HasError" Value="True"> <Setter Property="ToolTip" Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource Self}}"/> </Trigger> </Style.Triggers> </Style> </Application.Resources>
原理说明:
- ObservableValidator会在属性变更时自动触发数据注解验证,并通过
INotifyDataErrorInfo接口向WPF绑定系统发送错误通知。 - WPF的
Validation.ErrorTemplate用于定义验证失败时控件的可视化结构,AdornedElementPlaceholder会保留原控件的位置和样式,再叠加错误提示元素。 Validation.HasError触发器可根据错误状态修改控件的其他属性(如ToolTip)。
内容的提问来源于stack exchange,提问作者EnNico
相关产品推荐
相关产品推荐

