2

私は以下のようなWPFxamlコードを持っています:

  <StackPanel  FocusManager.FocusedElement="{Binding FocusedElement}">
    <TextBox Name="txtbox1" Text="FirstText"/>
    <TextBox Name="txtbox3" Text="SecondText"/>
    <TextBox Name="txtbox2" Text="ThirdText"/>
  </StackPanel>

どうすればFocusedElementをViewModelのプロパティにバインドできますか?以下の同様のコード:

Switch(Type)
{
Case "FirstType" :
  FocusedElement = "txtbox1";
break;
Case "SecondType" :
   FocusedElement = "txtbox2";
break;
Case "ThiredType" :
   FocusedElement = "txtbox3";
break;
}
4

2 に答える 2

6

ビューモデルはビューについて決して認識してはならず、いくつかの UIElement 名を認識していないことは間違いありません。しかし、ビューモデルが実際にフォーカスを管理できる必要がある場合 (先に進む前に、実際にそうであることを確認することをお勧めします)、次のようにすることができます。

ここに画像の説明を入力

ビューモデル:

public enum Focuses
{
    None = 0,
    First,
    Second,
    Third
}

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private Focuses _focusedElement;
    public Focuses FocusedElement { get { return _focusedElement; } set { _focusedElement = value; OnPropertyChanged("FocusedElement"); } }


    public ViewModel()
    {
        this.FocusedElement = Focuses.Second;
    }
}

Xaml:

<StackPanel >
    <TextBox Name="txtbox1" Text="FirstText"/>
    <TextBox Name="txtbox2" Text="SecondText"/>
    <TextBox Name="txtbox3" Text="ThirdText"/>
    <StackPanel.Style>
        <!-- cannot use DataTriggers directly in StackPanel.Triggers, therefore Style -->
        <Style TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding FocusedElement}" Value="First">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtbox1}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding FocusedElement}" Value="Second">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtbox2}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding FocusedElement}" Value="Third">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtbox3}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
</StackPanel>
于 2013-03-10T16:56:07.017 に答える
0

FocusedElement は、特定のフォーカス スコープに対して論理的なフォーカスを持つ要素です。

txtBox1.Focus(); などの「実際のフォーカス」ではなく、論理的なフォーカス。

論理フォーカスは複数回設定できますが、キーボード フォーカスを持つことができる要素は 1 つだけです。

論理的な焦点が本当に必要ですか?

GotFocus イベントをリッスンしてから、例としていくつかのカスタム ロジックを実行できます。

于 2013-03-10T10:17:26.340 に答える