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?
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?
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.
Wpf MVVM Used FocusExtension Behaviors
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
uie.Focus();
}
}
}
Xaml Code
<TextBox
behavior:FocusExtension.IsFocused="{Binding NameFocus}"
Text="{Binding Customer_Name,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }"
x:Name="txtname"
CharacterCasing="Upper"
Grid.Column="3"
Grid.Row="1"
TextWrapping="Wrap"
BorderThickness="1,1,1,0.5"
>
</TextBox>
MVVM Propery in View Model
public const string NameFocusPropertyName = "NameFocus";
private bool _NameFocus = default(bool);
public bool NameFocus
{
get
{
return _NameFocus;
}
set
{
if (_NameFocus == value)
{
return;
}
_NameFocus = value;
RaisePropertyChanged(NameFocusPropertyName);
}
}
Set Load Event
NameFocus=true
© 2022 - 2024 — McMap. All rights reserved.