【发布时间】: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