未能以编程方式将非空验证器添加到WPF组合框
为什么会失败 我有一个UserControl,其中包含一个组合框 我有一个名为“Mandatory”的属性,在没有选择的情况下,用户可以使用该属性添加验证 所以我在用户控件中有这样一个:未能以编程方式将非空验证器添加到WPF组合框,wpf,Wpf,为什么会失败 我有一个UserControl,其中包含一个组合框 我有一个名为“Mandatory”的属性,在没有选择的情况下,用户可以使用该属性添加验证 所以我在用户控件中有这样一个: public static DependencyProperty MandatoryProperty = DependencyProperty.Register("Mandatory", typeof(bool), typeof(CountyPicker), new PropertyMetadata
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的构造函数中写到控制台,忘记提到了!