动态更改FocusManager.FocusedElement

时间:2013-03-10 10:07:09

标签: wpf bind focusmanager

我有如下的WPF xaml代码:

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

如何在ViewModel中将FocusedElement绑定到属性?  类似的代码如下:

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

2 个答案:

答案 0 :(得分:5)

viewmodel永远不应该知道视图,当然也不知道一些UIElement名称。但鉴于viewmodel确实需要能够管理焦点(我建议你在继续之前确保确实如此),你可以这样做:

enter image description here

视图模型:

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>

答案 1 :(得分:0)

FocusedElement是具有特定焦点范围的逻辑焦点的元素。

逻辑焦点,而不是“真正的焦点”,如txtBox1.Focus();

逻辑焦点可以设置多次,而只有一个元素可以有键盘焦点。

你真的需要逻辑焦点吗?

您可以收听GotFocus事件,然后以自定义逻辑为例。