将焦点放在 WPF 视图模型中的 TextBox 上

我的视野里有一个 TextBox和一个 Button

现在,我在单击按钮时检查一个条件,如果条件为 false,则向用户显示消息,然后我必须将光标设置为 TextBox控件。

if (companyref == null)
{
var cs = new Lipper.Nelson.AdminClient.Main.Views.ContactPanels.CompanyAssociation();


MessageBox.Show("Company does not exist.", "Error", MessageBoxButton.OK,
MessageBoxImage.Exclamation);


cs.txtCompanyID.Focusable = true;


System.Windows.Input.Keyboard.Focus(cs.txtCompanyID);
}

上面的代码在 ViewModel 中。

CompanyAssociation是视图名称。

但是光标没有在 TextBox中设置。

答案是:

<igEditors:XamTextEditor Name="txtCompanyID"
KeyDown="xamTextEditorAllowOnlyNumeric_KeyDown"
ValueChanged="txtCompanyID_ValueChanged"
Text="{Binding Company.CompanyId,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
Width="{Binding ActualWidth, ElementName=border}"
Grid.Column="1" Grid.Row="0"
VerticalAlignment="Top"
HorizontalAlignment="Stretch"
Margin="0,5,0,0"
IsEnabled="{Binding Path=IsEditable}"/>


<Button Template="{StaticResource buttonTemp1}"
Command="{Binding ContactCommand}"
CommandParameter="searchCompany"
Content="Search"
Width="80"
Grid.Row="0" Grid.Column="2"
VerticalAlignment="Top"
Margin="0"
HorizontalAlignment="Left"
IsEnabled="{Binding Path=IsEditable}"/>
131743 次浏览

让我分三个部分来回答你的问题。

  1. 我想知道在您的示例中“ cs.txtCompanyID”是什么?它是 TextBox 控件吗?如果是的话,那你就走错路了。一般来说,在 ViewModel 中引用 UI 并不是一个好主意。你可以问“为什么”但这是 Stackoverflow 上要提出的另一个问题:)。

  2. 追踪 Focus 问题的最佳方法是... 调试。网络源代码。别开玩笑了。这节省了我很多时间。启动。Net 源代码调试请参考 肖恩 · 布鲁克 blog。

  3. 最后,我用来从 ViewModel 设置焦点的一般方法是附加属性。我编写了非常简单的附加属性,它可以在任何 UIElement 上设置。例如,它可以绑定到 ViewModel 的属性“ IsFocus”。这就是:

    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(); // Don't care about false values.
    }
    }
    }
    

    现在在您的视图(XAML)中,您可以将此属性绑定到 ViewModel:

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

Hope this helps :). If it doesn't refer to the answer #2.

Cheers.

System.Windows.Forms.Application.DoEvents();
Keyboard.Focus(tbxLastName);

问题是,一旦将 IsUserNameFocused 设置为 true,它就永远不会为 false。这通过处理 FrameworkElement 的 GotFocus 和 LostFocus 解决了这个问题。

我在源代码格式方面遇到了麻烦,所以这里是一个 链接

这些方法对我来说都不管用,但是为了其他人的利益,这是我最后根据这里已经提供的一些代码编写的代码。

用法如下:

<TextBox ... h:FocusBehavior.IsFocused="True"/>

执行情况如下:

/// <summary>
/// Behavior allowing to put focus on element from the view model in a MVVM implementation.
/// </summary>
public static class FocusBehavior
{
#region Dependency Properties
/// <summary>
/// <c>IsFocused</c> dependency property.
/// </summary>
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
typeof(FocusBehavior), new FrameworkPropertyMetadata(IsFocusedChanged));
/// <summary>
/// Gets the <c>IsFocused</c> property value.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>Value of the <c>IsFocused</c> property or <c>null</c> if not set.</returns>
public static bool? GetIsFocused(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool?)element.GetValue(IsFocusedProperty);
}
/// <summary>
/// Sets the <c>IsFocused</c> property value.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="value">The value.</param>
public static void SetIsFocused(DependencyObject element, bool? value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsFocusedProperty, value);
}
#endregion Dependency Properties


#region Event Handlers
/// <summary>
/// Determines whether the value of the dependency property <c>IsFocused</c> has change.
/// </summary>
/// <param name="d">The dependency object.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Ensure it is a FrameworkElement instance.
var fe = d as FrameworkElement;
if (fe != null && e.OldValue == null && e.NewValue != null && (bool)e.NewValue)
{
// Attach to the Loaded event to set the focus there. If we do it here it will
// be overridden by the view rendering the framework element.
fe.Loaded += FrameworkElementLoaded;
}
}
/// <summary>
/// Sets the focus when the framework element is loaded and ready to receive input.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private static void FrameworkElementLoaded(object sender, RoutedEventArgs e)
{
// Ensure it is a FrameworkElement instance.
var fe = sender as FrameworkElement;
if (fe != null)
{
// Remove the event handler registration.
fe.Loaded -= FrameworkElementLoaded;
// Set the focus to the given framework element.
fe.Focus();
// Determine if it is a text box like element.
var tb = fe as TextBoxBase;
if (tb != null)
{
// Select all text to be ready for replacement.
tb.SelectAll();
}
}
}
#endregion Event Handlers
}

对于那些尝试使用 Anvaka 的解决方案的人来说,我遇到的问题是绑定只在第一次运行时才起作用,因为 lostfocus 不会将属性更新为 false。您可以每次手动将属性设置为 false,然后再设置为 true,但是更好的解决方案可能是在属性中执行以下操作:

bool _isFocused = false;
public bool IsFocused
{
get { return _isFocused ; }
set
{
_isFocused = false;
_isFocused = value;
base.OnPropertyChanged("IsFocused ");
}
}

这样你只需要把它设置为真,它就会得到焦点。

我知道这个问题已经被回答了上千次了,但是我对 Anvaka 的贡献做了一些编辑,我认为这将帮助其他有类似问题的人。

首先,我改变了上面的附加属性,像这样:

public static class FocusExtension
{
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusExtension), new FrameworkPropertyMetadata(IsFocusedChanged){BindsTwoWayByDefault = true});


public static bool? GetIsFocused(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}


return (bool?)element.GetValue(IsFocusedProperty);
}


public static void SetIsFocused(DependencyObject element, bool? value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}


element.SetValue(IsFocusedProperty, value);
}


private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)d;


if (e.OldValue == null)
{
fe.GotFocus += FrameworkElement_GotFocus;
fe.LostFocus += FrameworkElement_LostFocus;
}


if (!fe.IsVisible)
{
fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
}


if (e.NewValue != null && (bool)e.NewValue)
{
fe.Focus();
}
}


private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)sender;
if (fe.IsVisible && (bool)fe.GetValue(IsFocusedProperty))
{
fe.IsVisibleChanged -= fe_IsVisibleChanged;
fe.Focus();
}
}


private static void FrameworkElement_GotFocus(object sender, RoutedEventArgs e)
{
((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
}


private static void FrameworkElement_LostFocus(object sender, RoutedEventArgs e)
{
((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
}
}

我添加可见性引用的原因是选项卡。显然,如果在初始可见选项卡之外的任何其他选项卡上使用附加属性,则附加属性直到您手动对控件进行聚焦时才能工作。

另一个障碍是创建一种更优雅的方法,在失去焦点时将底层属性重置为 false。这就是失焦事件发生的原因。

<TextBox
Text="{Binding Description}"
FocusExtension.IsFocused="{Binding IsFocused}"/>

如果有更好的办法解决能见度问题,请告诉我。

注意: 感谢 Apfelkuacha 建议将 BindsTwoWayByDefault 放在 DependencyProperty 中。我很久以前就在我自己的代码中这样做了,但是从来没有更新过这篇文章。由于这个更改,在 WPF 代码中不再需要 Mode = TwoWay。

我发现 至关重要解决可见性问题的方法非常有用。它没有完全解决我的问题,但是遵循相同模式的 IsEnable 模式的一些额外代码解决了问题。

对于 IsFocusedChanged 方法,我添加了:

    if (!fe.IsEnabled)
{
fe.IsEnabledChanged += fe_IsEnabledChanged;
}

接头人是这样的:

private static void fe_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)sender;
if (fe.IsEnabled && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
{
fe.IsEnabledChanged -= fe_IsEnabledChanged;
fe.Focus();
}
}

我认为最好的方法是保持 MVVM 原理的简洁, 所以基本上你必须使用 MVVM Light 提供的 Messenger 类,下面是如何使用它:

在你的视图模型中( exampleviewmodel.cs ) :

 Messenger.Default.Send<string>("focus", "DoFocus");

现在,在 View.cs (不是 XAML,而是 view.XAML.cs)中,在构造函数中编写以下内容

 public MyView()
{
InitializeComponent();


Messenger.Default.Register<string>(this, "DoFocus", doFocus);
}
public void doFocus(string msg)
{
if (msg == "focus")
this.txtcode.Focus();
}

这种方法运行良好,代码更少,并维护 MVVM 标准

在我的例子中,在我更改方法 OnIsFocusedPropertyChanged 之前,FocusExtension 无法工作。当一个断点停止进程时,原来的程序只能在调试中工作。在运行时,过程太快,什么都不会发生。通过这个小小的修改和我们的朋友 Task 的帮助,这在两种情况下都能很好地工作。

private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
var action = new Action(() => uie.Dispatcher.BeginInvoke((Action)(() => uie.Focus())));
Task.Factory.StartNew(action);
}
}

我使用 WPF/Caliburn Micro 发现“ dfaivre”提供了一个通用的、可行的解决方案 这里: Http://caliburnmicro.codeplex.com/discussions/222892

对于 Silverlight:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;


namespace MyProject.Behaviors
{
public class FocusBehavior : Behavior<Control>
{
protected override void OnAttached()
{
this.AssociatedObject.Loaded += AssociatedObject_Loaded;
base.OnAttached();
}


private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
if (this.HasInitialFocus || this.IsFocused)
{
this.GotFocus();
}
}


private void GotFocus()
{
this.AssociatedObject.Focus();
if (this.IsSelectAll)
{
if (this.AssociatedObject is TextBox)
{
(this.AssociatedObject as TextBox).SelectAll();
}
else if (this.AssociatedObject is PasswordBox)
{
(this.AssociatedObject as PasswordBox).SelectAll();
}
else if (this.AssociatedObject is RichTextBox)
{
(this.AssociatedObject as RichTextBox).SelectAll();
}
}
}


public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.Register(
"IsFocused",
typeof(bool),
typeof(FocusBehavior),
new PropertyMetadata(false,
(d, e) =>
{
if ((bool)e.NewValue)
{
((FocusBehavior)d).GotFocus();
}
}));


public bool IsFocused
{
get { return (bool)GetValue(IsFocusedProperty); }
set { SetValue(IsFocusedProperty, value); }
}


public static readonly DependencyProperty HasInitialFocusProperty =
DependencyProperty.Register(
"HasInitialFocus",
typeof(bool),
typeof(FocusBehavior),
new PropertyMetadata(false, null));


public bool HasInitialFocus
{
get { return (bool)GetValue(HasInitialFocusProperty); }
set { SetValue(HasInitialFocusProperty, value); }
}


public static readonly DependencyProperty IsSelectAllProperty =
DependencyProperty.Register(
"IsSelectAll",
typeof(bool),
typeof(FocusBehavior),
new PropertyMetadata(false, null));


public bool IsSelectAll
{
get { return (bool)GetValue(IsSelectAllProperty); }
set { SetValue(IsSelectAllProperty, value); }
}


}
}

Loginviewmodel.cs :

    public class LoginModel : ViewModelBase
{
....


private bool _EmailFocus = false;
public bool EmailFocus
{
get
{
return _EmailFocus;
}
set
{
if (value)
{
_EmailFocus = false;
RaisePropertyChanged("EmailFocus");
}
_EmailFocus = value;
RaisePropertyChanged("EmailFocus");
}
}
...
}

登录:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:beh="clr-namespace:MyProject.Behaviors"


<TextBox Text="{Binding Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Behaviors>
<beh:FocusBehavior IsFocused="{Binding EmailFocus}" IsSelectAll="True"/>
</i:Interaction.Behaviors>
</TextBox>

或者

<TextBox Text="{Binding Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Behaviors>
<beh:FocusBehavior HasInitialFocus="True" IsSelectAll="True"/>
</i:Interaction.Behaviors>
</TextBox>

要设置焦点,只需在代码中进行:

EmailFocus = true;

请记住,这个插件是 html 页面的一部分,因此页面中的其他控件可能具有焦点

if (!Application.Current.IsRunningOutOfBrowser)
{
System.Windows.Browser.HtmlPage.Plugin.Focus();
}

您可以使用 ViewCommand设计模式。它描述了一种用于 MVVM 设计模式的方法,该方法通过命令来控制 ViewModel 中的 View。

我根据 King A.Majid 关于使用 MVVM Light Messenger 类的建议实现了它。ViewCommandManager 类处理连接视图中的调用命令。它基本上是常规命令的另一个方向,在这些情况下,当 ViewModel 需要在其 View 中执行某些操作时。它使用像数据绑定命令和 WeakReferences 这样的反射来避免内存泄漏。

Http://dev.unclassified.de/source/viewcommand (亦载于 CodeProject)

Anvakas 精彩的代码适用于 Windows 桌面应用程序。如果你像我一样,需要同样的解决方案,Windows 商店应用程序这段代码可能会很方便:

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 PropertyMetadata(false, OnIsFocusedPropertyChanged));




private static void OnIsFocusedPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
var uie = d as Windows.UI.Xaml.Controls.Control;


if( uie != null )
{
uie.Focus(FocusState.Programmatic);
}
}
}
}

我已经找到了解决方案,编辑代码,如下所示。不需要先设置 Binding 属性 False 然后 True。

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)
{
if (d != null && d is Control)
{
var _Control = d as Control;
if ((bool)e.NewValue)
{
// To set false value to get focus on control. if we don't set value to False then we have to set all binding
//property to first False then True to set focus on control.
OnLostFocus(_Control, null);
_Control.Focus(); // Don't care about false values.
}
}
}


private static void OnLostFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control)
{
(sender as Control).SetValue(IsFocusedProperty, false);
}
}
}
public class DummyViewModel : ViewModelBase
{
private bool isfocused= false;
public bool IsFocused
{
get
{
return isfocused;
}
set
{
isfocused= value;
OnPropertyChanged("IsFocused");
}
}
}

这是一个老线程,但似乎没有解决问题的代码与阿纳万卡的接受的答案: 它不工作,如果你设置的属性在视图模型为假,或如果你设置你的属性为真,用户手动点击别的东西,然后你设置它为真。在这种情况下,我也无法让 Zamtic 的解决方案可靠地工作。

将上面的一些讨论结合起来,我得到了下面的代码,它确实解决了这些问题,我认为:

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, null, OnCoerceValue));


private static object OnCoerceValue(DependencyObject d, object baseValue)
{
if ((bool)baseValue)
((UIElement)d).Focus();
else if (((UIElement) d).IsFocused)
Keyboard.ClearFocus();
return ((bool)baseValue);
}
}

话虽如此,但是对于可以在代码隐藏中用一行代码完成的事情来说,这仍然很复杂,而且 CoerceValue 实际上并不打算以这种方式使用,所以也许代码隐藏才是解决问题的方法。

似乎没有人包含最后一个步骤,使得通过绑定变量更新属性变得容易。这是我想到的。如果有更好的办法,请告诉我。

XAML

    <TextBox x:Name="txtLabel"
Text="{Binding Label}"
local:FocusExtension.IsFocused="{Binding txtLabel_IsFocused, Mode=TwoWay}"
/>


<Button x:Name="butEdit" Content="Edit"
Height="40"
IsEnabled="{Binding butEdit_IsEnabled}"
Command="{Binding cmdCapsuleEdit.Command}"
/>

ViewModel

    public class LoginModel : ViewModelBase
{


public string txtLabel_IsFocused { get; set; }
public string butEdit_IsEnabled { get; set; }




public void SetProperty(string PropertyName, string value)
{
System.Reflection.PropertyInfo propertyInfo = this.GetType().GetProperty(PropertyName);
propertyInfo.SetValue(this, Convert.ChangeType(value, propertyInfo.PropertyType), null);
OnPropertyChanged(PropertyName);
}




private void Example_function(){


SetProperty("butEdit_IsEnabled", "False");
SetProperty("txtLabel_IsFocused", "True");
}


}

首先我要感谢 Avanka 帮助我解决了我的注意力问题。然而,他发布的代码中有一个 bug,即: 如果(e. OldValue = = null)

我遇到的问题是,如果您首先在视图中单击并对控件进行聚焦,那么 e.oldValue 就不再为 null。然后,当您第一次设置变量以使控件聚焦时,这将导致未设置 lostfocus 和 gotfocus 处理程序。 我的解决办法如下:

public static class ExtensionFocus
{
static ExtensionFocus()
{
BoundElements = new List<string>();
}


public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
typeof(ExtensionFocus), new FrameworkPropertyMetadata(false, IsFocusedChanged));


private static List<string> BoundElements;


public static bool? GetIsFocused(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("ExtensionFocus GetIsFocused called with null element");
}
return (bool?)element.GetValue(IsFocusedProperty);
}


public static void SetIsFocused(DependencyObject element, bool? value)
{
if (element == null)
{
throw new ArgumentNullException("ExtensionFocus SetIsFocused called with null element");
}
element.SetValue(IsFocusedProperty, value);
}


private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)d;


// OLD LINE:
// if (e.OldValue == null)
// TWO NEW LINES:
if (BoundElements.Contains(fe.Name) == false)
{
BoundElements.Add(fe.Name);
fe.LostFocus += OnLostFocus;
fe.GotFocus += OnGotFocus;
}




if (!fe.IsVisible)
{
fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
}


if ((bool)e.NewValue)
{
fe.Focus();
}
}


private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)sender;


if (fe.IsVisible && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
{
fe.IsVisibleChanged -= fe_IsVisibleChanged;
fe.Focus();
}
}


private static void OnLostFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control s)
{
s.SetValue(IsFocusedProperty, false);
}
}


private static void OnGotFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control s)
{
s.SetValue(IsFocusedProperty, true);
}
}
}

照我说的做:

<Window x:class...
...
...
FocusManager.FocusedElement="{Binding ElementName=myTextBox}"
>
<Grid>
<TextBox Name="myTextBox"/>
...

在实现了公认的答案之后,我确实遇到了一个问题: 当使用 Prism 导航视图时,TextBox 仍然无法获得焦点。PropertyChanged 处理程序的一个小更改解决了这个问题

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
uie.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
{
uie.Focus();
}));
}
}

一种基于@Sheridan 答案的替代方法

 <TextBox Text="{Binding SomeText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding SomeTextIsFocused, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>

在视图模型中,按照通常的方式设置绑定,然后将 Some TextIsFocus 设置为 true,以便将焦点设置在文本框上