0

为什么会失败?

我有一个包含 ComboBox 的 UserControl。

我有一个名为“强制”的属性,如果没有选择,用户可以使用它添加验证。

所以我在用户控件中有这个:

public static DependencyProperty MandatoryProperty
  = DependencyProperty.Register("Mandatory", typeof(bool), typeof(CountyPicker),
    new PropertyMetadata((bool)false, OnChangedMandatoryByBinding));

private static void OnChangedMandatoryByBinding
  (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  var value = (bool)e.NewValue;

  ((CountyPicker)d).OnChangedMandatoryByBinding(value);
}

public bool Mandatory
{
  get { return (bool)GetValue(MandatoryProperty); }
  set { SetValue(MandatoryProperty, value); }
}

public void OnChangedMandatoryByBinding(bool value)
{
  var binding = BindingOperations.GetBinding
    (TheComboBox, ComboBox.SelectedItemProperty);

  binding.ValidationRules.Clear();

  if (value == true) // strange that I need this without getting a warning
  {
    binding.ValidationRules.Add(new NotNullValidator());
  }
}

该 xaml 包含:

<UserControl x:Class="Foo.Controls.Pickers.CountyPicker"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <ComboBox Name="TheComboBox"
      KeyDown="TheComboBox_KeyDown"
      SelectedItem="{Binding County,Mode=TwoWay}" />
</UserControl>

但是虽然 Mandatory 的值是这样设置的:

<p:CountyPicker Mandatory="True"
  CountyCode="{Binding customer.CountyCode, Mode=TwoWay}"/>

...似乎没有进行验证。我在 NotNullValidator:s Validate 方法中设置了一个断点,但没有命中。

4

0 回答 0