viewmodel 永远不应该知道视图,而且肯定不知道某些 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;
}
}
xml:
<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>