WPF绑定到自定义控件(文本)不工作 [英] WPF binding to custom control (textbox) not working

查看:417
本文介绍了WPF绑定到自定义控件(文本)不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了从TextBox继承和使用自定义输入框输入文字简单的自定义控制:

i wrote a simple custom control that inherits from textbox and uses a custom inputbox to enter text:

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

我用它在像这样的观点:

i use it in the view like this:

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

在虚拟机的测试:

in the vm for tests:

private string _test;
public string Test
    {
        get { return _test; }
        set
        {
            if (_test == value)
                return;
            _test = value;
            RaisePropertyChanged("Test");
        }
    }

测试不工作的结合。在视图中,我看到的文本框的文本没有改变,但我似乎并没有被连接到虚拟机的性能。我加入 MessageBox.Show(测试)按钮,但它始终是空的。我究竟做错了什么?

but the binding to Test is not working. in the view, i see that the text of the textbox does change, but i seems not to be linked to the property of the VM. i added a button with MessageBox.Show(Test), but it is always empty. what am i doing wrong here?

推荐答案

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

You need to set the binding's UpdateSourceTrigger property to PropertyChanged. Otherwise the source property Test will not be updated before the TextBox loses focus.

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


例子的上的 Binding.UpdateSourceTrigger 在MSDN页:


From the Examples section on the Binding.UpdateSourceTrigger page on MSDN:

该TextBox.Text酒店的默认UpdateSourceTrigger值
  引发LostFocus。这意味着,如果一个应用程序有一个文本框
  数据绑定TextBox.Text属性,键入文本框中的文本
  直到文本框失去焦点(不更新源
  例如,当你在文本框点击即可)。

The TextBox.Text property has a default UpdateSourceTrigger value of LostFocus. This means if an application has a TextBox with a data-bound TextBox.Text property, the text you type into the TextBox does not update the source until the TextBox loses focus (for instance, when you click away from the TextBox).

这篇关于WPF绑定到自定义控件(文本)不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆