简体   繁体   中英

WPF Style Validation Trigger Command

I have some dynamic generated Textboxes with Validators. I want them to send a Command to VM, if a validation error occurs. This Behavior is placed in a style, so I don't need to write it into the xaml generation.

Here's the Code:

<behaviors:Triggers x:Key="validationTrigger" x:Shared="False">
    <behaviors:ValidationErrorEventTrigger>
        <cmd:EventToCommand Command="{Binding ValidationError,NotifyOnValidationError=True}"
                            PassEventArgsToCommand="True" />
    </behaviors:ValidationErrorEventTrigger>
</behaviors:Triggers>

<Style x:Key="EditableTextBox" TargetType="{x:Type TextBox}">
    <Setter Property="Background" Value="#DDFFDD" />
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <Border BorderBrush="Red" BorderThickness="2">
                    <AdornedElementPlaceholder />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="behaviors:OCCInteraction.Triggers" Value="{StaticResource ResourceKey=validationTrigger}" />
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="Background" Value="#FFDDDD"/>
        </Trigger>
    </Style.Triggers>
</Style>

The Problem I'm having now, is that the "Onvalidation" Event is called in the VlidationErrorEventTrigger class, but the Command isn't called in the Viewmodel. I've tested it with a direct integration and not with a style and it works this way.

So maybe it has something to do with the Binding of the Command or so...

I hope this description is enough to solve the Problem. If not please tell me :)

I am not sure how you binding is done but assuming that DataContext of you `Control/Window has your ViewModel Instance and ValidationError` is your command...

<behaviors:Triggers x:Key="validationTrigger" x:Shared="False">
 <behaviors:ValidationErrorEventTrigger>
     <cmd:EventToCommand Command="{Binding Path=DataContext.ValidationError,RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}",NotifyOnValidationError=True}"                     
    PassEventArgsToCommand="True" />
 </behaviors:ValidationErrorEventTrigger>
</behaviors:Triggers>

This is assuming that your trigger is not able to find the command required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM