Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.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
C# 为什么不是';是否正在执行我的WPF验证规则?_C#_Wpf_Validation_Xaml - Fatal编程技术网

C# 为什么不是';是否正在执行我的WPF验证规则?

C# 为什么不是';是否正在执行我的WPF验证规则?,c#,wpf,validation,xaml,C#,Wpf,Validation,Xaml,我不想讲更大的故事,但是我有一个表单上的组合框,它没有/没有正常工作。为了尝试通过实验解决问题,我创建了一个测试WPF项目,并将所有相关代码添加到一个简单的WPF窗口中 在我的原始表单上,当组合框上的SelectedValue更改时,我可以根据需要执行我的ValidationRule。然而,在将代码复制并粘贴到这个新项目中之后,我可以编译并运行程序而不出错,但我无法让验证器执行 可以肯定的是,我在代码中都放了断点。在我的ValidationRule中,我永远不能点击Validate(…)方法,我

我不想讲更大的故事,但是我有一个表单上的组合框,它没有/没有正常工作。为了尝试通过实验解决问题,我创建了一个测试WPF项目,并将所有相关代码添加到一个简单的WPF窗口中

在我的原始表单上,当组合框上的
SelectedValue
更改时,我可以根据需要执行我的ValidationRule。然而,在将代码复制并粘贴到这个新项目中之后,我可以编译并运行程序而不出错,但我无法让验证器执行

可以肯定的是,我在代码中都放了断点。在我的
ValidationRule
中,我永远不能点击
Validate(…)
方法,我也不明白为什么这不起作用。特别是因为这是一个直接复制和粘贴,只需要少量的、最小的名称空间更新,以满足明显的引用需求,而且这在我的原始应用程序中确实有效

下面是所有相关的代码。可以随意复制、粘贴和运行

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);
        }
    }
}
使用系统;
使用System.Collections.ObjectModel;
使用System.Linq;
使用系统组件模型;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
命名空间WPFDataGridApp13
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
myEntityComboBox.SelectedIndex=0;
myEntityComboBox.ItemsSource=new[]
{
新的{myEntityId=(int?)null,myEntityName=“null选项”},
新的{myEntityId=(int?)1,myEntityName=“#1”},
新的{myEntityId=(int?)2,myEntityName=“#2”}
};
Binding b=BindingOperations.GetBinding(myEntityComboBox、ComboBox.SelectedValueProperty);
b、 ValidationRules.Clear();
b、 Add(新的WPFDataGridApp13.NonNullValidator());
}
private void myEntityComboBox_SelectionChanged(对象发送方,SelectionChangedEventArgs e)
{
}
私有无效按钮\u单击(对象发送者,路由目标e)
{
myEntityComboBox.SelectedIndex=0;
}
}
公共类非NullValidator:ValidationRule
{
公共覆盖验证结果验证(对象值,System.Globalization.CultureInfo CultureInfo)
{
返回值==null
?新的ValidationResult(错误,“Gruu!”)
:新的ValidationResult(true,null);
}
}
}
请注意,我的
NotNullValidator
的XAML声明是我最初指定验证器的方法,也是我设置此属性的首选方法

我已经注释了它,并在我的代码隐藏文件中设置了验证器,但这也不起作用。无论我尝试什么,我都无法在我的
非空验证器
类上点击
验证
方法


发生了什么事?

您的绑定有一些问题。请参阅下面的代码。您需要将所选组合值绑定到某个属性

<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);
    }
}