如何检查ItemsControl中的所有文本框是否有效

时间:2017-10-22 12:35:36

标签: c# wpf datatemplate relaycommand validationrule

我有一个itemscontrol的模板:

<DataTemplate DataType="{x:Type models:StringParameter}">
         <TextBox materialDesign:HintAssist.Hint="{Binding Name}">
             <TextBox.Text>
                 <Binding Path="Value">
                     <Binding.ValidationRules>
                         <ınteractiveCode:NotEmptyValidationRule ValidatesOnTargetUpdated="True"></ınteractiveCode:NotEmptyValidationRule>
                     </Binding.ValidationRules>
                 </Binding>
             </TextBox.Text>
         </TextBox>
     </DataTemplate>

我有一个使用命令的按钮,我希望在ItemsControl中满足所有验证时启用它。但我无法找到一种方法来访问内部数据模板中的文本框。

1 个答案:

答案 0 :(得分:1)

我有一个简单的方法来解决这个具体问题。我创建了一个ValidationChecker类,它将使用IsValid方法检查是否存在验证错误。

public class ValidationChecker : Freezable
{
    public static List<DependencyObject> elements = new List<DependencyObject>();

    public static int GetValidationObject(DependencyObject obj)
    {
        return (int)obj.GetValue(ValidationObjectProperty);
    }

    public static void SetValidationObject(DependencyObject obj, int value)
    {
        obj.SetValue(ValidationObjectProperty, value);
    }

    // Using a DependencyProperty as the backing store for ErrorCount.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ValidationObjectProperty =
        DependencyProperty.RegisterAttached("ValidationObject", typeof(DependencyObject), typeof(ValidationChecker), new PropertyMetadata(null, OnValueChanged));


    public static bool IsValid()
    {
        foreach (var item in elements)
        {
            if (Validation.GetHasError(item)) return false;
        }
        return true;
    }

    private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        elements.Add(d);
    }

    protected override Freezable CreateInstanceCore()
    {
        return new ValidationChecker();
    }
}

ValidationObject附加属性可以像下面这样实现

<DataTemplate>
    <TextBox local:ValidationChecker.ValidationObject="{Binding RelativeSource={RelativeSource Self}}">
         <TextBox.Text>
             <Binding Path="Value">
                 <Binding.ValidationRules>
                      <local:NotEmptyValidationRule ValidatesOnTargetUpdated="True"></local:NotEmptyValidationRule>
                 </Binding.ValidationRules>
              </Binding>
          </TextBox.Text>
       </TextBox>
</DataTemplate>

您已经提到您的Button已绑定到Command。因此,为CanExecute实施Command方法并调用ValidationChecker.Isvalid()。在您需要时,不要忘记为此RaiseCanExecute调用Command方法。