mvvmdata-bindingwpf-controlswpf-4.5

Setting focus to UI control in WPF MVVM Way on Validation.HasError


Problem: Validation.HasError automatically highlights the control that has Error via INotifyDataErrorInfo implementation.

My problem is i need to set focus on that specific control when it has ERror.

How do I do That?


Solution

  • I have gone through several articles in Stackoverflow and other sites and i finally wish to address this problem.

       <Style TargetType="TextBox" >
                            <Setter Property="OverridesDefaultStyle" Value="false"/>
                            <Setter Property="VerticalAlignment" Value="Center"/>
                            <Setter Property="HorizontalAlignment" Value="Left"/>
                            <Setter Property="Margin" Value="5,3" />
                            <Style.Triggers>
                                <Trigger Property="Validation.HasError" Value="True">
                                    <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
    

    Setting FocusedElement did the trick. :) This can also be used to set focus using a boolean property in ViewModel via DataTrigger than a simple trigger.