118

ExceptionValidationRuleWPFでは、またはを使用して、データバインディング中にデータレイヤーでスローされたエラーに基づいて検証を設定できますDataErrorValidationRule

この方法で多数のコントロールを設定し、[保存]ボタンを使用したとします。ユーザーが[保存]ボタンをクリックした場合、保存を続行する前に、検証エラーがないことを確認する必要があります。検証エラーがある場合は、それらを大声で叫びます。

WPFでは、データバインドコントロールのいずれかに検証エラーが設定されているかどうかをどのように確認しますか?

4

10 に答える 10

141

この投稿は非常に役に立ちました。貢献してくれたすべての人に感謝します。これは、好き嫌いの分かれる LINQ バージョンです。

private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = IsValid(sender as DependencyObject);
}

private bool IsValid(DependencyObject obj)
{
    // The dependency object is valid if it has no errors and all
    // of its children (that are dependency objects) are error-free.
    return !Validation.GetHasError(obj) &&
    LogicalTreeHelper.GetChildren(obj)
    .OfType<DependencyObject>()
    .All(IsValid);
}
于 2011-01-10T18:59:56.813 に答える
50

次のコード (Chris Sell と Ian Griffiths によるプログラミング WPF ブックから) は、依存関係オブジェクトとその子に対するすべてのバインディング ルールを検証します。

public static class Validator
{

    public static bool IsValid(DependencyObject parent)
    {
        // Validate all the bindings on the parent
        bool valid = true;
        LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();
        while (localValues.MoveNext())
        {
            LocalValueEntry entry = localValues.Current;
            if (BindingOperations.IsDataBound(parent, entry.Property))
            {
                Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                foreach (ValidationRule rule in binding.ValidationRules)
                {
                    ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);
                    if (!result.IsValid)
                    {
                        BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                        System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));
                        valid = false;
                    }
                }
            }
        }

        // Validate all the bindings on the children
        for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (!IsValid(child)) { valid = false; }
        }

        return valid;
    }

}

ページ/ウィンドウでこのように保存ボタンクリックイベントハンドラーでこれを呼び出すことができます

private void saveButton_Click(object sender, RoutedEventArgs e)
{

  if (Validator.IsValid(this)) // is valid
   {

    ....
   }
}
于 2008-09-24T16:56:22.280 に答える
16

同じ問題があり、提供された解決策を試しました。H-Man2とskiba_kのソリューションの組み合わせは、1つの例外を除いて、ほとんど問題なく機能しました。私のウィンドウにはTabControlがあります。また、検証ルールは、現在表示されているTabItemに対してのみ評価されます。そこで、VisualTreeHelperをLogicalTreeHelperに置き換えました。今では動作します。

    public static bool IsValid(DependencyObject parent)
    {
        // Validate all the bindings on the parent
        bool valid = true;
        LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();
        while (localValues.MoveNext())
        {
            LocalValueEntry entry = localValues.Current;
            if (BindingOperations.IsDataBound(parent, entry.Property))
            {
                Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                if (binding.ValidationRules.Count > 0)
                {
                    BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                    expression.UpdateSource();

                    if (expression.HasError)
                    {
                        valid = false;
                    }
                }
            }
        }

        // Validate all the bindings on the children
        System.Collections.IEnumerable children = LogicalTreeHelper.GetChildren(parent);
        foreach (object obj in children)
        {
            if (obj is DependencyObject)
            {
                DependencyObject child = (DependencyObject)obj;
                if (!IsValid(child)) { valid = false; }
            }
        }
        return valid;
    }
于 2009-10-23T12:06:54.333 に答える
7

Dean の優れた LINQ 実装に加えて、コードを DependencyObjects の拡張機能にラップするのが楽しかったです。

public static bool IsValid(this DependencyObject instance)
{
   // Validate recursivly
   return !Validation.GetHasError(instance) &&  LogicalTreeHelper.GetChildren(instance).OfType<DependencyObject>().All(child => child.IsValid());
}

これは、再利用性を考慮すると非常に優れています。

于 2012-10-31T22:06:53.457 に答える
2

私は小さな最適化を提供します。

同じコントロールに対してこれを何度も行う場合は、上記のコードを追加して、実際に検証ルールを持つコントロールのリストを保持できます。次に、有効性を確認する必要があるときはいつでも、ビジュアルツリー全体ではなく、これらのコントロールのみに目を通します。このようなコントロールが多数ある場合、これははるかに優れていることがわかります。

于 2010-07-01T08:40:31.737 に答える
2

これは、WPF でのフォーム検証用のライブラリです。Nuget パッケージはこちら.

サンプル:

<Border BorderBrush="{Binding Path=(validationScope:Scope.HasErrors),
                              Converter={local:BoolToBrushConverter},
                              ElementName=Form}"
        BorderThickness="1">
    <StackPanel x:Name="Form" validationScope:Scope.ForInputTypes="{x:Static validationScope:InputTypeCollection.Default}">
        <TextBox Text="{Binding SomeProperty}" />
        <TextBox Text="{Binding SomeOtherProperty}" />
    </StackPanel>
</Border>

アイデアは、添付されたプロパティを介して検証スコープを定義し、どの入力コントロールを追跡するかを伝えるというものです。次に、次のことができます。

<ItemsControl ItemsSource="{Binding Path=(validationScope:Scope.Errors),
                                    ElementName=Form}">
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type ValidationError}">
            <TextBlock Foreground="Red"
                       Text="{Binding ErrorContent}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
于 2016-02-10T11:19:37.423 に答える
0

回答フォーム aogan では、検証ルールを明示的に繰り返すのではなく、呼び出すだけでよいexpression.UpdateSource():

if (BindingOperations.IsDataBound(parent, entry.Property))
{
    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
    if (binding.ValidationRules.Count > 0)
    {
        BindingExpression expression 
            = BindingOperations.GetBindingExpression(parent, entry.Property);
        expression.UpdateSource();

        if (expression.HasError) valid = false;
    }
}
于 2009-07-06T06:42:45.467 に答える
0

WPF アプリケーション フレームワーク (WAF)のBookLibraryサンプル アプリケーションに興味があるかもしれません。WPF で検証を使用する方法と、検証エラーが存在する場合に [保存] ボタンを制御する方法を示します。

于 2010-08-16T17:19:46.470 に答える
0

すべてのコントロール ツリーを再帰的に反復処理し、添付プロパティ Validation.HasErrorProperty を確認してから、最初に見つけたものに焦点を当てることができます。

既に作成された多くのソリューションを使用することもできます。例と詳細については、このスレッドを確認してください。

于 2008-09-24T14:29:35.033 に答える