如果我在TextBox中编辑文本然后按Enter键以激活默认密钥的Click事件,我就不会在Click处理程序中获得正确的值。
如何在我的处理程序中获取此值?
这是我的xaml:
<Window x:Class="WpfApplication1.DefaultKeyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DefaultKeyWindow" Height="300" Width="300">
<StackPanel>
<TextBox Text="{Binding test}" />
<Button Click="OnOk" IsDefault="True">OK</Button>
</StackPanel>
</Window>
这里我的代码背后:
public partial class DefaultKeyWindow : Window
{
public string test
{
get { return (string)GetValue(testProperty); }
set { SetValue(testProperty, value); }
}
// Using a DependencyProperty as the backing store for test. This enables animation, styling, binding, etc...
public static readonly DependencyProperty testProperty =
DependencyProperty.Register("test", typeof(string), typeof(DefaultKeyWindow), new PropertyMetadata("initial value"));
public DefaultKeyWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void OnOk(object sender, RoutedEventArgs e)
{
MessageBox.Show("Value of test is " + test);
DialogResult = true;
}
}
答案 0 :(得分:1)
默认情况下,TextBox
在失去焦点之前不会更新Binding
。您可以通过设置UpdateSourceTrigger
:
<TextBox Text="{Binding test, UpdateSourceTrigger=PropertyChanged}" />