Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未能以编程方式将非空验证器添加到WPF组合框_Wpf - Fatal编程技术网

未能以编程方式将非空验证器添加到WPF组合框

未能以编程方式将非空验证器添加到WPF组合框,wpf,Wpf,为什么会失败 我有一个UserControl,其中包含一个组合框 我有一个名为“Mandatory”的属性,在没有选择的情况下,用户可以使用该属性添加验证 所以我在用户控件中有这样一个: public static DependencyProperty MandatoryProperty = DependencyProperty.Register("Mandatory", typeof(bool), typeof(CountyPicker), new PropertyMetadata

为什么会失败

我有一个UserControl,其中包含一个组合框

我有一个名为“Mandatory”的属性,在没有选择的情况下,用户可以使用该属性添加验证

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

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>

但是,尽管强制值设置如下:

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


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

does
binding.ValidationRules.Add(new NotNullValidator())曾经被调用过吗?是的,我已经在NotNullValidator的构造函数中写到控制台,忘记提到了!