wpf - Validation.ErrorTemplate 未显示

标签 wpf validation mvvm user-controls

我有一个 MainWindow 和一个 UserControl。 MainWindow 显示 UserControl。
UserControl 本身遵循 MVVM 模式并在 ViewModel 中实现 IDataErrorInfo 接口(interface)。这工作正常,但 Validation.ErrorTemplate 没有显示。

我的 UserControl.xaml

 <TextBox x:Name="txtName" 
          Text="{Binding Path=Name, Mode=TwoWay, 
                 UpdateSourceTrigger=PropertyChanged, 
                 ValidatesOnDataErrors=True}" 
          Grid.Row="0" Grid.Column="2"
          VerticalAlignment="Bottom" MinWidth="100" FontSize="12">
       <TextBox.Resources>
           <Style TargetType="TextBox">
               <Setter Property="Validation.ErrorTemplate">
                   <Setter.Value>
                       <ControlTemplate>
                           <StackPanel Orientation="Horizontal">
                               <AdornedElementPlaceholder>
                                   <Border BorderBrush="Red" BorderThickness="1"/>
                               </AdornedElementPlaceholder>
                           </StackPanel>
                       </ControlTemplate>
                   </Setter.Value>
               </Setter>
           <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>
       </TextBox.Resources>
   </TextBox>

ToolTip 显示正确,但 TextBox 的红色边框仅在我使用 Snoop 并在 VisualTree 中选择 TextBox 时显示。

所以我错过了什么?任何触发器?

我在两本书中查找了这一点,并尝试了正在运行的示例。那么根据 UserControl,这是一个错误,我必须以某种方式手动更新它吗?

编辑
现在,当我只以这种方式使用它时,我完全感到困惑:
<TextBox x:Name="txtName" 
    Text="{Binding Path=Name, Mode=TwoWay, 
            UpdateSourceTrigger=PropertyChanged, 
            ValidatesOnDataErrors=True}" 
      Grid.Row="0" Grid.Column="2"
      VerticalAlignment="Bottom" MinWidth="100" FontSize="12">
    <TextBox.Resources>
        <Style TargetType="TextBox">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="True">
                <Setter Property="ToolTip" 
                    Value="{Binding RelativeSource={RelativeSource Self},
                                Path=(Validation.Errors)[0].ErrorContent}"/>
                <Setter Property="BorderBrush" Value="Red"/>
                <Setter Property="BorderThickness" Value="3"/>
            </Trigger>
        </Style.Triggers>
        </Style>
    </TextBox.Resources>
</TextBox>

BorderBrush 和 BorderThickness 总是“红色”/“3”!为什么或如何触发将其设置回来?
根据这个:
Only false style displaying when using Validation.HasError trigger property WPF
清除 Validation.HasError 时应显示默认值。

最佳答案

所以我发现了我的错误,(或者至少是为什么 Validation.HasError 永远不会重置的部分原因)我以错误的方式使用了 IDataErrorInfo 接口(interface)。
如果验证通过,我没有返回 null 或 String.Empty。 :(

    //Not used in WPF so return value is null
    string IDataErrorInfo.Error { get { return null; } }

    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            //the wrong way
            string error = "false way";
            //the right way
            string error = null;
            //or
            string error = String.Empty;

            switch (propertyName)
            {
                case ("name"):
                    if (string.IsNullOrEmpty(name) || name.Trim() == String.Empty)
                    {
                        error = "Enter name";
                    }
                    break;
                case ("age"):
                    if (string.IsNullOrEmpty(age) || age.Trim() == String.Empty)
                    {
                        error = "Enter age";
                    }
                    break;
                default:
                    Debug.Fail("Validation: Unexpected property: " + propertyName);
                    break;
            }
            return error;
        }
    }

编辑
有时我得到这个错误,没有修剪......

System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'ValidationError') from '(Validation.Errors)' (type 'ReadOnlyObservableCollection`1'). BindingExpression:Path=(0)[0].ErrorContent; DataItem='TextBox' (Name='txtName'); target element is 'TextBox' (Name='txtName'); target property is 'ToolTip' (type 'Object') ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException: Das angegebene Argument liegt außerhalb des gültigen Wertebereichs. Parametername: index'

关于wpf - Validation.ErrorTemplate 未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25037993/

相关文章:

c# - WPF 设置窗口数据上下文

php - 如何使 CodeIgniter 可调用留空的复选框,自定义表单验证错误

asp.net - 构建时验证所有 ASPX、ASCX 和 HTML 文件

android - 最佳实践 : Runtime filters with Room and LiveData

wpf - 如何在 WPF 中更改按钮 MouseOver 的背景?

wpf - mvvm中的businesslogic

wpf - 尝试查找功能区控件资源字典时出错 - Office2007Blue

java - 我可以根据 XSD 验证 XML 元素的数据类型、大小写、长度和空检查吗?

android - MutableLivedata 观察者触发

wpf - xamdatagrid有条件地禁用列