Last active
April 20, 2021 06:43
-
-
Save yoshikazuendo/e49e172728694210203bfb051ea182b1 to your computer and use it in GitHub Desktop.
【WPF】【MVVM】MVVMでControlのFocusを指定する。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Focus用behaviorを作ってあげて、それを利用するのが良さそう。 | |
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- usage --> | |
<!-- ViewModelにIsSelectedプロパティを用意してあげて、その値を変更することでbehaviorが走り、Focusが変わる。 --> | |
<TextBox my:FocusExtension.IsFocused="{Binding IsSelected}" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment