WPF binding to custom control (textbox) not working

爱⌒轻易说出口 提交于 2020-01-06 08:52:15

问题


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

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?


回答1:


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}" ... />

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

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).



来源:https://stackoverflow.com/questions/25863674/wpf-binding-to-custom-control-textbox-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!