6

複数のテキストボックスを持つグリッドがあります。ユーザーがフォーカスする可能性のあるアクションに応じて、テキスト ボックスの 1 つに変更する必要があります。私の現在のソリューションでは、ViewModel の文字列プロパティと xaml のデータ トリガーを使用してフォーカスを変更しています。それはうまく機能しますが、これを達成するのはかなり回りくどい方法のように思われるので、より明確な方法で行うことができるかどうか疑問に思っていましたか?

    <Grid.Style>
        <Style TargetType="Grid">
            <Style.Triggers>
                <DataTrigger Binding="{Binding FocusedItem}" Value="number">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=number}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding FocusedItem}" Value="name">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=name}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding FocusedItem}" Value="id">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=id}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>

ご覧のとおり、プロパティの値と要素の名前は同じなので、要素ごとに 1 つのトリガーを使用するのではなく、単一のトリガーでこれを実行したいと考えています。

多分誰かがよりクリーンな方法を思い付くことができますか?

前もって感謝します

4

1 に答える 1

4

私のプロジェクトの 1 つでフォーカスを設定する方法は、フォーカス拡張機能を使用することでした (元の投稿をどこで見たか覚えていないことをお詫びします)。

    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 ファイルで依存関係プロパティとして使用します。

<TextBox Uid="TB1" FontSize="13" localExtensions:FocusExtension.IsFocused="{Binding Path=TB1Focus}" Height="24" HorizontalAlignment="Left" Margin="113,56,0,0" Name="TB_UserName" VerticalAlignment="Top" Width="165" Text="{Binding Path=TB1Value, UpdateSourceTrigger=PropertyChanged}" />

その後、バインディングを使用してフォーカスを設定できます。

于 2013-03-13T00:38:33.733 に答える