Observable 验证器在 wpf 中不起作用

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

我正在使用 wpf mvvm 应用程序,我也使用 Community toolkit.mvvm 。 这里我为文本框实现了 Observable 验证器,但它不会影响用户界面,

视图模型:

 public partial class UserViewModel :  ObservableValidator
    {
        [ObservableProperty]
        [Required(ErrorMessage ="Name is Required")]
        [MinLength(3)]
        private string name= "";
    }

Xaml:

  <TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

当我在文本框中输入少于3个字符并保留它时,它不起作用, 文本框接受每个范围内的字符,也接受空字符。

c# wpf mvvm desktop-application community-toolkit-mvvm
2个回答
4
投票

谢谢你! @mm8

先生

我只是错过了一个属性,-->

[NotifyDataErrorInfo]

现在可以正常工作了。

视图模型:

 public partial class UserViewModel :  ObservableValidator
 {
    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Required(ErrorMessage ="Name is Required")]
    [MinLength(3, ErrorMessage ="Name Should be at least 3 character")]
    private string username;
 }

Xaml:

 <TextBox Text="{Binding Username, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

1
投票

确认绑定正常。不需要将绑定的

ValidatesOnDataErrors
属性设置为
true

<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged,
    ValidatesOnDataErrors=True}"/>
© www.soinside.com 2019 - 2024. All rights reserved.