gpt4 book ai didi

输入键上的 WPF 验证

转载 作者:行者123 更新时间:2023-12-04 13:35:22 24 4
gpt4 key购买 nike

当按下 Enter 键时,我正在尝试验证 UI 更改。 UI 元素是一个文本框,它是绑定(bind)到字符串的数据。我的问题是当 Enter 键为 Up 时,数据绑定(bind)没有更新 TestText。只有当我按下弹出消息框的按钮时才会更新。

/// <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"

文本框 XAML:
TextBox Name="myTextBox" Text="{Binding TestText}"

按钮 XAML:
Button Name="button1" Click="button1_Click"

最佳答案

为了强制 TextBox 将值提交回绑定(bind)源,您可以执行以下操作:

var binding = myTextBox.GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();

或者,您可以配置绑定(bind)以在每次 Text 属性更改时更新源,这意味着您在文本框中输入的每个字符。
<TextBox Name="myTextBox"
Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" />

但这会引发很多属性更改通知。我在我的应用程序中所做的是创建一个派生自 TextBox 的类来覆盖 OnKeyDown方法,当按下回车键时,我调用 UpdateSource我上面描述的方法,也调用 SelectAll在 TextBox 上给用户一个我刚刚“接受”他们的输入的想法。从 TextBox 派生一个类将允许您在应用程序中可能需要的任何其他地方重用该行为。

关于输入键上的 WPF 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2671684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com