She*_*dan 12
通常,当我们想要在遵守MVVM方法的同时使用UI事件时,我们创建一个Attached Property:
public static DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(TextBoxProperties), new UIPropertyMetadata(false, OnIsFocusedChanged));
public static bool GetIsFocused(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject dependencyObject, bool value)
{
dependencyObject.SetValue(IsFocusedProperty, value);
}
public static void OnIsFocusedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
TextBox textBox = dependencyObject as TextBox;
bool newValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
bool oldValue = (bool)dependencyPropertyChangedEventArgs.OldValue;
if (newValue && !oldValue && !textBox.IsFocused) textBox.Focus();
}
Run Code Online (Sandbox Code Playgroud)
此属性使用如下:
<TextBox Attached:TextBoxProperties.IsFocused="{Binding IsFocused}" ... />
Run Code Online (Sandbox Code Playgroud)
然后我们可以TextBox通过将IsFocused属性更改为以下内容来关注视图模型true:
IsFocused = false; // You may need to set it to false first if it is already true
IsFocused = true;
Run Code Online (Sandbox Code Playgroud)