WPF验证输入密钥 [英] WPF validation on Enter Key Up
问题描述
当我按Enter键时,我试图验证一个UI改变。 UI元素是一个文本框,它是绑定到字符串的数据。我的问题是,当Enter键为Up时,数据绑定没有更新TestText。只有当我按下显示消息框的按钮时才更新。
I'm trying to validate a UI change when Enter key is pressed. The UI element is a textbox, which is data binded to a string. My problem is that the data binding hasn't updated TestText when Enter key is Up. It is only updated when I press the button which brings up a message box.
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window, INotifyPropertyChanged
{
String _testText = new StringBuilder("One").ToString();
public string TestText
{
get { return _testText; }
set { if (value != _testText) { _testText = value; OnPropertyChanged("TestText"); } }
}
public Window1()
{
InitializeComponent();
myGrid.DataContext = this;
}
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void onKeyUp(object sender, KeyEventArgs e)
{
if (e.Key != System.Windows.Input.Key.Enter) return;
System.Diagnostics.Trace.WriteLine(TestText);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(TestText);
}
}
窗口XAML:
Window x:Class="VerificationTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" KeyUp="onKeyUp"
TextBox XAML:
TextBox XAML:
TextBox Name="myTextBox" Text="{Binding TestText}"
按钮XAML:
Button Name="button1" Click="button1_Click"
推荐答案
为了强制TextBox将值提交给绑定源,您可以执行以下操作: / p>
In order to force the TextBox to commit the value back to the binding source you can do:
var binding = myTextBox.GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
或者,您可以配置绑定以在每次Text属性更改时更新源,这意味着您输入到文本框中的每个字符。
Optionally, you can configure the binding to update the source every time the Text property changes which would mean on every character you enter into the text box.
<TextBox Name="myTextBox"
Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" />
但这会引发很多属性更改通知。我在我的应用程序中做的是创建一个派生自TextBox的类来覆盖 OnKeyDown
方法,并且按下Enter键后,我调用 UpdateSource
方法,并且在TextBox上调用 SelectAll
,给用户一个想法,即接受他们的输入。从TextBox中派生一个类,可以让您将该行为重用于您在应用程序中可能需要的任何地方。
But this will raise a lot of property change notifications. What I have done in my applications was to create a class derived from TextBox to override the OnKeyDown
method and when enter is pressed, I call the UpdateSource
method as I described above and also call SelectAll
on the TextBox to give the user an idea that I just "accepted" their input. Deriving a class from TextBox will let you reuse that behavior anywhere else you might want it in your application.
这篇关于WPF验证输入密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!