简体   繁体   English

在 WPF 的 ValidationRules 中设置自定义错误消息

[英]Set custom error message in ValidationRules in WPF

I have set everything perfectly.我已经完美地设置了一切。 If I set some string in ErrorMessage then it shows without error.如果我在 ErrorMessage 中设置了一些字符串,那么它会显示没有错误。 在此处输入图像描述

What I want is, I want to set ErrorMessage dynamically/programmatically.我想要的是,我想动态/以编程方式设置 ErrorMessage 。 something某物

MyValidation.ErrorMessage = "some new message";
username.Update() //something


XAML Code XAML 代码

<TextBox Margin="5" Name="userName">
   <TextBox.Text>
      <Binding RelativeSource="{RelativeSource Self}" Path="Tag" Mode="OneWayToSource" UpdateSourceTrigger="PropertyChanged">
         <Binding.ValidationRules>
            <local:MyValidation ErrorMessage="Static String" />
         </Binding.ValidationRules>
      </Binding>
   </TextBox.Text>
</TextBox>


C# Class Code C# Class 代码

public class MyValidation : ValidationRule {
   public string ErrorMessage { get; set; }

   public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
      if (ErrorMessage.Length > 0) {
         return new ValidationResult(false, ErrorMessage);
      }
      return ValidationResult.ValidResult;
   }
}

You can implement INotifyDataErrorInfo in your viewmodel.您可以在视图模型中实现INotifyDataErrorInfo Implement GetErrors(string) so it returns different error messages based on your condition.实施GetErrors(string)以便它根据您的情况返回不同的错误消息。 You can even return multiple messages at once and they will be displayed below each other.您甚至可以一次返回多条消息,它们将显示在彼此下方。

Here's a nice tutorial , but feel free to implement it on your own.这是一个很好的教程,但您可以自己实现它。 Keep in mind that there's not just one correct approach and the interface gives you a lot of freedom.请记住,不仅有一种正确的方法,而且界面为您提供了很大的自由度。

If you give the ValidationRule a name in the XAML markup:如果您在 XAML 标记中为ValidationRule命名:

<Binding.ValidationRules>
    <local:MyValidation x:Name="val" ErrorMessage="Static String" />
</Binding.ValidationRules>

...you could set its ErrorMessage property directly and then just explicitly update the binding: ...您可以直接设置其ErrorMessage属性,然后显式更新绑定:

val.ErrorMessage = "some new message";
userName.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM