-
[WPF]FocusC#/WPF 2022. 12. 23. 15:56
보통사용
<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
728x90'C# > WPF' 카테고리의 다른 글
[WPF] {Binding} (0) 2023.02.03 [WPF] xmlns (0) 2023.02.02 [WPF]Close UserControl Window in ViewModel with Module (0) 2022.12.23 [WPF] Uri (0) 2022.12.20 [WPF] WPF 동작 구조 (0) 2022.12.16 댓글