WPF绑定到自定义控件(文本框)不工作

WPF绑定到自定义控件(文本框)不工作,wpf,binding,custom-controls,Wpf,Binding,Custom Controls,我编写了一个简单的自定义控件,该控件继承自textbox,并使用自定义inputbox输入文本: class TextTextbox : TextBox { public string InputBoxTitle { get; set; } public string Input { get; set; } public TextTextbox() { PreviewMouseDown += MyTextbox_MouseDown;

我编写了一个简单的自定义控件,该控件继承自textbox,并使用自定义inputbox输入文本:

class TextTextbox : TextBox
{

    public string InputBoxTitle { get; set; }

    public string Input { get; set; }

    public TextTextbox()
    {
        PreviewMouseDown += MyTextbox_MouseDown;
    }

    private void MyTextbox_MouseDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
    {
        TextBox tb = (TextBox)sender;
        var dialog = new BFH.InputBox.InputBox(InputBoxTitle, Input);
        dialog.ShowDialog();

        if (!dialog.Canceled)
            tb.Text = dialog.Input;
        else
            tb.Text = Input;
    }
}
我在视图中使用它,如下所示:

<CustomControls:TextTextbox Text="{Binding Test}" InputBoxTitle="Titel" Input="Input"/>

但是与
测试的绑定不起作用。在视图中,我看到文本框的文本确实发生了变化,但我似乎没有链接到VM的属性。我添加了一个带有
MessageBox.Show(Test)
的按钮,但它总是空的。我这里做错了什么?

您需要将绑定的
UpdateSourceTrigger
属性设置为
PropertyChanged
。否则,在文本框失去焦点之前,将不会更新源属性
Test

<CustomControls:TextTextbox
    Text="{Binding Test, UpdateSourceTrigger=PropertyChanged}" ... />


从MSDN页面的示例部分:

Text属性的默认UpdateSourceTrigger值为 失去焦点。这意味着如果应用程序有一个带有 数据绑定TextBox.Text属性,在TextBox中键入的文本 在文本框失去焦点之前不更新源(对于 实例,当您从文本框中单击时)


您确定控件中有一些
DataContext
?它将用作
绑定的隐式
@user3815356测试,使用
Text=“{Binding}”
,它将打印
数据上下文
,只需注意:在派生的TextBox类中,不必将事件处理程序附加到类的“own
PreviewMouseDown
事件。您可以只覆盖受保护的
OnPreviewMouseDown
方法。
<CustomControls:TextTextbox
    Text="{Binding Test, UpdateSourceTrigger=PropertyChanged}" ... />