开发者

Why does the data binding in this validation example work?

开发者 https://www.devze.com 2022-12-24 07:34 出处:网络
I\'m wondering how exactly the XAML sample (MSDN sample) works: <Style x:Key=\"textBoxInError\" TargetType=\"{x:Type TextBox}\">

I'm wondering how exactly the XAML sample (MSDN sample) works:

<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="true">
    <Setter Property="ToolTip"
    Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                    Path=(Validation.Errors)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
 </Style>

Questions:

  • (Validation.Errors)[0].ErrorContent - Is this code somehow checked by WPF? Because Validation.Errors may be an empty collection and in ordinary C# code this code may throw an exception. If this data-binding returns null for valid input - the null value is then casted to empty string (开发者_Python百科in a text control for example)?
  • The index 0 corresponds to the first error message. How can I return more error messages from Validate method?

Thank you for responses!


In this case, your binding is only active when Validation.HasError is true (based on the Trigger). Because of this, there is always going to be at least one error in your collection.

If you want to display more than the first error, you could instead put a control inside of your Tooltip that allows you to bind to the entire collection, such as a ListView. This would let you have a ListView's ItemsSource bound to the collection of Validation.Errors instead of trying to access only the first.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号