【问题标题】:WPF Validation Rule on ComboBox calling the Setter of binded propery twiceComboBox上的WPF验证规则两次调用绑定属性的Setter
【发布时间】:2020-07-29 19:00:29
【问题描述】:

我有一个这样的组合框:

<ComboBox Name="TipoVisitante" ItemsSource="{Binding TiposVisitante}" SelectedValue="{Binding TipoVisitante}" Style="{StaticResource ComboBoxStyle}">
   <ComboBox.Text>
      <Binding Path="TipoVisitante" UpdateSourceTrigger="PropertyChanged">
         <Binding.ValidationRules>
            <validations:SimpleIsRequiredValidation/>
         </Binding.ValidationRules>
      </Binding>
   </ComboBox.Text>
</ComboBox>

此 ComboBox 绑定到 ViewModel 的 TipoVisitante 属性。 TipoVisitante 变量如下所示:

private string _TipoVisitante;
public string TipoVisitante {
  get =>_TipoVisitante;
  set {
    if (ValidarTipoVisita(value) == true) {
      _TipoVisitante = value;
      OnPropertyChanged();
    }
    else {
      MessageBox.Show("YA EXISTE UNA VISITA ÍNTIMA ACTIVA", "VISITA INTIMA ACTIVA", MessageBoxButton.OK, MessageBoxImage.Error);
      _TipoVisitante = null;
      OnPropertyChanged();
    }
  }
}

设置 TipoVisitante 时,我想使用返回 true 或 false 的方法检查该值是否有效,具体取决于该值是否有效。如果这些值无效,我会显示一条消息,指出该值无效。问题是,由于 ComboBox 上的规则验证,TipoVisitante 变量的 set 属性被调用了两次,并且错误消息显示了两次。 ComboBox 的验证规则如下所示:

public class SimpleIsRequiredValidation: ValidationRule {
  public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
    if (!string.IsNullOrEmpty(value ? .ToString())) 
       return new ValidationResult(true, null);
    else 
       return new ValidationResult(false, null);
  }
}

验证规则检查用户是否选择了组合框的某个值,检查文本是否为空或空字符串。在我后面的代码中也有这个:

private void Button_Click(object sender, RoutedEventArgs e) {
  if (string.IsNullOrWhiteSpace(TipoVisitante.Text)) 
     TipoVisitante.Text = "";
}

此方法是按钮的 Click 属性。单击按钮时,我检查用户是否没有选择 ComboBox 的某些值我将文本设置为空字符串以触发验证并在 ComboBox 中显示红色边框。

如何避免绑定变量TipoVisitante的setter被调用两次?

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    尝试添加额外的属性,检查它是否被调用一次,然后使用它来阻止调用它两次。

    【讨论】:

      【解决方案2】:

      解决方案是将验证从 ComboBox.Text 更改为 ComboBox.SelectedValue。之后在按钮单击操作中,将TipoVisitante.Text = "" 更改为TipoVisitante.SelectedValue = null。这样做效果很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        相关资源
        最近更新 更多