【问题标题】:WPF validation on Enter Key Up输入键上的 WPF 验证
【发布时间】:2010-04-19 23:55:21
【问题描述】:

我正在尝试在按下 Enter 键时验证 UI 更改。 UI 元素是一个文本框,它是绑定到字符串的数据。我的问题是当 Enter 键为 Up 时,数据绑定没有更新 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"

【问题讨论】:

标签: wpf data-binding


【解决方案1】:

为了强制 TextBox 将值提交回绑定源,您可以这样做:

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

或者,您可以配置绑定以在每次 Text 属性更改时更新源,这意味着您在文本框中输入的每个字符。

<TextBox Name="myTextBox"
         Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" />

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

【讨论】:

  • 谢谢...它适用于我的简单演示案例。如果我有很多这样的 UI 元素,有关如何强制更新的任何提示?
  • 参考我的编辑。我刚刚添加了一个创建从 TextBox 派生的类的建议。您可以在 WPF 中使用行为、附加的依赖属性、命令等十几种方法来实现它,但我认为按照我建议的方式在派生类中实现它是最简单的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多