LoginSignup
7
11

More than 5 years have passed since last update.

フォーカスについて

Last updated at Posted at 2017-07-11

フォーカスの概要

MSDN

初期フォーカスのセット

FocusManager.FocusedElementを使用する。

sample.xaml
<Grid  FocusManager.FocusedElement="{Binding ElementName=*****}" >

ViewModelからのフォーカスセット

バインドできるプロパティを作成する。

FocusExtension.cs
    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();
            }
        }
    }
ViewModel
        public bool IsTextBoxFocused
        {
            get { return _isFocused; }
            set
            {
                this.SetProperty(ref this._isFocused, value);
            }
        }
View

<TextBox local:FocusExtension.IsFocused="{Binding IsTextBoxFocused}" /> 

Behaviorでフォーカスセット

FocusBehavior.cs
{
    public class FocusBehavior : Behavior<FrameworkElement>
    {
        /// <summary>
        /// フォーカス設定
        /// </summary>
        public void Focus()
        {
            this.AssociatedObject.Focus();
        }
    }
sample.xaml
        <CheckBox Content="flg1" HorizontalAlignment="Left" IsChecked="{Binding Flg1}">
            <i:Interaction.Behaviors>
                <local:FocusBehavior x:Name="forcusTest" />
            </i:Interaction.Behaviors>
        </CheckBox>
        <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Command="{Binding CalcCommand}" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ei:CallMethodAction TargetObject="{Binding ElementName=forcusTest}" MethodName="Focus" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>

Tabキーでの移動

TabIndex プロパティを指定する。
参考URL

7
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
11