Setting focus to UI control in WPF MVVM Way on Val

2019-06-10 00:04发布

问题:

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?

回答1:

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.