为什么我的WPF ValidationRule没有被执行?

时间:2015-03-05 19:01:22

标签: c# wpf validation xaml

我会把更大的故事放在一边,但我在表格上有一个ComboBox并没有表现得很好。为了尝试通过实验解决问题,我创建了一个测试WPF项目,并将所有相关代码添加到一个简单的WPF窗口。

在原始表单上,当ComboBox上的SelectedValue发生更改时,我可以根据需要执行ValidationRule。但是,在将代码复制并粘贴到这个新项目之后,我可以编译并运行程序而不会出现错误,但是我无法执行验证程序?

可以肯定的是,我在整个代码中都设置了断点。我永远无法点击Validate(...)中的ValidationRule方法,我无法理解为什么这不起作用。特别是因为这是一个直接的复制和粘贴,只有少数,最小的命名空间更新,以满足明显的参考需求,这肯定在我原来的应用程序中工作。

以下是所有相关代码。随意复制,粘贴和运行。

XAML

<Window Height="270" 
        Title="MainWindow" 
        Width="532" 
        x:Class="WPFDataGridApp13.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:my="clr-namespace:WPFDataGridApp13"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="True">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>
        <ControlTemplate x:Key="validationTemplate">
            <Grid>
                <Border BorderThickness="1" BorderBrush="Red" >
                    <AdornedElementPlaceholder />
                </Border>
            </Grid>
        </ControlTemplate>
    </Window.Resources>
    <StackPanel>
        <ComboBox x:Name="myEntityComboBox"              
                          DisplayMemberPath="myEntityName" SelectedValuePath="myEntityId"
                          Validation.ErrorTemplate="{StaticResource validationTemplate}"
                          VerticalAlignment="Center"  Margin="5">
            <ComboBox.SelectedValue>
                <Binding Path="myEntityId" 
                                 Mode="TwoWay" 
                                 NotifyOnValidationError="True" 
                                 NotifyOnTargetUpdated="True" 
                                 NotifyOnSourceUpdated="True" 
                                 ValidatesOnExceptions="True" 
                                 ValidatesOnDataErrors="True"
                                 UpdateSourceTrigger="PropertyChanged">
                    <!--<Binding.ValidationRules>
                        <my:NonNullValidator/>
                    </Binding.ValidationRules>-->
                </Binding>
            </ComboBox.SelectedValue>
        </ComboBox>
        <Button Content="Select a null value." Click="Button_Click"   Margin="5"/>
    </StackPanel>
</Window>

幕后代码

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace WPFDataGridApp13
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            myEntityComboBox.SelectedIndex = 0;
            myEntityComboBox.ItemsSource = new[]
            {
                new { myEntityId = (int?)null, myEntityName="Null Option"},
                new { myEntityId = (int?)1, myEntityName="#1"},
                new { myEntityId = (int?)2, myEntityName="#2"}
            };
            Binding b = BindingOperations.GetBinding(myEntityComboBox, ComboBox.SelectedValueProperty);
            b.ValidationRules.Clear();
            b.ValidationRules.Add(new WPFDataGridApp13.NonNullValidator());
        }

        private void myEntityComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            myEntityComboBox.SelectedIndex = 0;
        }
    }

    public class NonNullValidator : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            return value == null
                ? new ValidationResult(false, "Gruu!")
                : new ValidationResult(true, null);
        }
    }
}

快速说明,我的NotNullValidator的XAML声明是我原始的指定验证器的方法,是我设置此属性的首选方法。

我已经对它进行了评论并在我的代码后面设置了验证器,但是它也没有用。无论我尝试什么,我都无法点击Validate课程中的NonNullValidator方法。

发生了什么?

1 个答案:

答案 0 :(得分:1)

您的绑定存在一些问题。参考下面的代码。您需要将选定的组合值绑定到某个属性。

<Window x:Class="IconicZip_Learning.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="clr-namespace:IconicZip_Learning"
    Title="Window1" Height="300" Width="300">
<Window.Resources>
    <Style TargetType="ComboBox">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="True">
                <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
            </Trigger>
        </Style.Triggers>
    </Style>
    <ControlTemplate x:Key="validationTemplate">
        <Grid>
            <Border BorderThickness="1" BorderBrush="Red" >
                <AdornedElementPlaceholder />
            </Border>
        </Grid>
    </ControlTemplate>
</Window.Resources>
<StackPanel>
    <ComboBox x:Name="myEntityComboBox"              
                      DisplayMemberPath="myEntityName" SelectedValuePath="myEntityId"
                      Validation.ErrorTemplate="{StaticResource validationTemplate}"
                      VerticalAlignment="Center"  Margin="5">
        <ComboBox.SelectedValue>
            <Binding Path="SelectedEntity" 
                     RelativeSource="{RelativeSource Mode=FindAncestor,
                                                     AncestorType=Window}"
                             Mode="TwoWay" 
                             NotifyOnValidationError="True" 
                             NotifyOnTargetUpdated="True" 
                             NotifyOnSourceUpdated="True" 
                             ValidatesOnExceptions="True" 
                             ValidatesOnDataErrors="True"
                             UpdateSourceTrigger="Default"
                             >
                <Binding.ValidationRules>
                    <my:NonNullValidator ValidatesOnTargetUpdated="True"/>
                </Binding.ValidationRules>
            </Binding>
        </ComboBox.SelectedValue>
    </ComboBox>
    <Button Content="Select a null value." Click="Button_Click"   Margin="5"/>
</StackPanel>

public partial class Window1 : Window,INotifyPropertyChanged
{

    private int? myVar;

    public int? SelectedEntity
    {
        get { return myVar; }
        set { myVar = value; OnPropChanged("SelectedEntity"); }
    }


    public Window1()
    {
        InitializeComponent();
        myEntityComboBox.ItemsSource = new[]
        {
            new { myEntityId = (int?)null, myEntityName="Null Option"},
            new { myEntityId = (int?)1, myEntityName="#1"},
            new { myEntityId = (int?)2, myEntityName="#2"}
        };
        myEntityComboBox.SelectedIndex = 0;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

    }

    private void myEntityComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        myEntityComboBox.SelectedIndex = 0;
    }
}
public class NonNullValidator : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        return value == null
            ? new ValidationResult(false, "Gruu!")
            : new ValidationResult(true, null);
    }
}