1

I have a custom class in which I've implemented INotifyPropertyChanged and I can happily bind this to the .Text property of a TextBox on a form and have the data flow both ways.

I'm now trying to achieve the same thing with a textbox on a usercontrol, via a property:

public string MyProperty
{
    get { return MyPropertyTextBox.Text; }
    set { MyPropertyTextBox.Text = value; }
}

I can bind my class to the MyProperty on the Usercontrol so that the value is set.

But how do I get it so that when I edit the textbox the change is fed back to my class?

Edit:

Not sure I explained myself very well + it's WinForms, not WPF.

The text box itself isn't bound, I wanted the 'TextChanged' event of the textbox to also trigger 'PropertyChanged' of the usercontrol property. Built myself a proof of concept test, got that working, and then managed to implement it in my project.

thanks for the suggestions though.

4

3 回答 3

3

将该方法添加OnPropertyChanged到您的属性中。像这样的东西:

private string _myPropertyText;
public string MyProperty
{       
    get { return _myPropertyText; }
    set { 
         if(_myPropertyText != value) 
         {
            _myPropertyText = value; 
            OnPropertyChanged("MyPropertyTextBox");
         }
        }
}

您没有在问题中提到 XAML,但正如 @RetailCoder 所指出的,您的 XAML 也需要正确设置,就像 Alan 的回答一样。

<TextBox Text="{Binding myProperty,UpdateSourceTrigger=PropertyChanged}" 
于 2013-10-04T19:10:51.493 回答
1

如果您希望它在编辑时更新,请使用此 xaml

<TextBox Text="{Binding myproperty,UpdateSourceTrigger=PropertyChanged}" 
于 2013-10-04T19:12:13.657 回答
-2

当您直接从 textbox.Text 准备好时,将直接检测到任何更改,无需额外代码

于 2013-10-04T19:02:02.700 回答