1

如果我在 TextBox 中编辑文本,然后按 Enter 键以触发默认键的 Click 事件,我在 Click 处理程序中没有得到正确的值。

如何在我的处理程序中获取此值?

这是我的xml:

<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;
    }
}
4

1 回答 1

1

默认情况下, a在失去焦点之前TextBox不会更新。Binding您可以通过设置以下内容轻松解决此问题UpdateSourceTrigger

<TextBox Text="{Binding test, UpdateSourceTrigger=PropertyChanged}" />
于 2013-08-15T14:29:15.373 回答