输入键上的 WPF 验证

标签 wpf data-binding

当按下 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/

相关文章:

asp.net - 在 aspx 中的 <%# %> 标签内可以访问哪些其他对象?

java - 在 Java 中删除 json 中的节点

wpf - 尝试创建允许文本选择的 WPF 标签模板时出现格式问题

c# - WPF:修剪所有文本框

c# - WebClient() 可以同时下载多个字符串吗?

wpf - 如何在 XAML 中构建控件网格?

javascript - 如何在 Handlebars.js 模板上绑定(bind)数据以自动更新值?

wpf - 如何在 XAML 中增加 SymbolIcon 的大小?

wpf - 在 Storyboard 中设置 ViewModel bool 属性

data-binding - 在没有 v-model 和数据绑定(bind)的情况下为输入赋值