views:

50

answers:

1

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 (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!

+1  A: 

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.

Reed Copsey
Oh, you're right. I was confused by the book I'm reading (where is very similar snippet) where the part with "Validation.HasErrors" is missing and it really throws an exception even though the author states it shouldn't.But how can I send more errors via the return value of Validate method?
MartyIX
@MartyIX: That's really a separate question, but it depends on how you're handling validation. If you are trying to validate yourself, look into IDataErrorInfo - you can have the validation occur that way, plus the "standard" validation.
Reed Copsey
@Reed: Actually I don't have my own validation - I'm starting with WPF and this was a sample from my book. I was just curious. Thank you for your answer.
MartyIX