C#/WPF
[WPF] Focus, TabIndex
딸기우유중독
2022. 12. 23. 15:56
TabIndex
TabIndex 먹이는데 작동이 잘 안되면
관련 된 Control에 여러개(전부) TabIndex 주면 먹힘.
Focus
보통사용
<TextBox FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" />
작동 안할시 아래
확실히 잘 됨.
아래 코드 심층공부 필요O
의존성 주입 공부 필요
public static class FocusExtension
{
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusExtension), new FrameworkPropertyMetadata(IsFocusedChanged) { BindsTwoWayByDefault = true });
public static bool? GetIsFocused(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool?)element.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject element, bool? value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsFocusedProperty, value);
}
private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)d;
if (e.OldValue == null)
{
fe.GotFocus += FrameworkElement_GotFocus;
fe.LostFocus += FrameworkElement_LostFocus;
}
if (!fe.IsVisible)
{
fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
}
if (e.NewValue != null && (bool)e.NewValue)
{
fe.Focus();
}
}
private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)sender;
if (fe.IsVisible && (bool)fe.GetValue(IsFocusedProperty))
{
fe.IsVisibleChanged -= fe_IsVisibleChanged;
fe.Focus();
}
}
private static void FrameworkElement_GotFocus(object sender, RoutedEventArgs e)
{
((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
}
private static void FrameworkElement_LostFocus(object sender, RoutedEventArgs e)
{
((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
}
}
<TextBox
Text="{Binding Description}"
FocusExtension.IsFocused="{Binding IsFocused}"/>
https://stackoverflow.com/questions/1356045/set-focus-on-textbox-in-wpf-from-view-model
Set focus on TextBox in WPF from view model
I have a TextBox and a Button in my view. Now I am checking a condition upon button click and if the condition turns out to be false, displaying the message to the user, and then I have to set the
stackoverflow.com
728x90