无法以编程方式将非null验证程序添加到WPF ComboBox

时间:2012-08-23 14:07:41

标签: wpf

为什么会失败?

我有一个包含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:的Validate方法中放了一个断点,但是没有命中。

0 个答案:

没有答案