[英]How do I check if all textboxes inside ItemsControl are valid
I have this template for an 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>
And I have a button that works with a command, I want it to get enabled when all validations are met in ItemsControl.我有一个与命令一起使用的按钮,我希望在 ItemsControl 中满足所有验证时启用它。 But I can't find a way to reach textboxes which are inside data templates.
但是我找不到到达数据模板内的文本框的方法。
I have a simple approach to solve this specific issue.我有一个简单的方法来解决这个特定问题。 I have created a
ValidationChecker
class that will check for existence of validation errors using IsValid
method.我创建了一个
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
attached property can be implemented as like below 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>
You have already mentioned that your Button
has been bind to a Command
.您已经提到您的
Button
已绑定到Command
。 So implement CanExecute
method for the Command
and call ValidationChecker.Isvalid()
.因此,为
Command
实现CanExecute
方法并调用ValidationChecker.Isvalid()
。 Don't forget to invoke RaiseCanExecute
method for this Command
whenever you need.不要忘记在需要时为此
Command
调用RaiseCanExecute
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.