OnOk中未设置依赖项属性

时间:2013-08-15 14:22:07

标签: .net wpf data-binding

如果我在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;
    }
}

1 个答案:

答案 0 :(得分:1)

默认情况下,TextBox在失去焦点之前不会更新Binding。您可以通过设置UpdateSourceTrigger

轻松解决此问题
<TextBox Text="{Binding test, UpdateSourceTrigger=PropertyChanged}" />