Reputation: 1454
C#, VS-2010, winforms
Generally I want to create user control with a bindable MyProperty. But I met some problem: Data row become modified when current row changed.
You can download C# project and try it yourself: test_bind.zip
To make it simple I did follow:
all standard steps, nothing special
Run
as expected - rows in dgv, current name in textBox, click on different rows in grid... and only when I modify text in textbox I stop in breakpoint.
Lets modify program, and bind textBox to different property instead of Text - lets say Tag. Set DataSourceUpdateProperty "OnValidation" or "OnPropertyChanged".
Run
Now current row become modified. !!!
Same happens when instead of textBox I use UserControl with a dummy property
String MyProperty { set; get; }
How to bind custom property in user control with the same behaviour as TextBox.Text?
Note: Binding property itself is not a problem. Problem is: when I bind to standard TextBox.Text property - everything Ok Wen I bind to ANY OTHER property (Tag) or to custom Property in User Control - then DATASOURCE ALWAYS BECOME MODIFIED FOR CURRENT ROW
Upvotes: 0
Views: 1985
Reputation: 1454
Short answer is:
When bind to simple property, declared like
[Bindable(true, BindingDirection.TwoWay)] // I need TwoWay
public String MyProp {set;get;}
then datasource will be updated on current position change. You may count it as Bug or Feature...
To change behavior - I need magic word. Declare event in the control as
public event System.ComponentModel.PropertyChangedEventHandler MyPropChanged;
This name is special: "YourPropertyName" + "Changed" = YourPropertyNameChanged Other word will not be magic. As soon as event declared - datasource would not be updated every time as before...
and now I can control the process...
public void OnMyPropChanged(System.ComponentModel.PropertyChangedEventArgs e)
{
Binding bb = this.DataBindings[0] as Binding;
bb.WriteValue();
if (MyPropChanged != null) MyPropChanged(this, e);
}
private void TxtChanged(object sender, EventArgs e)
{
if (load) { return; }
_my_prop = Txt.Text; // ...
OnValueTwoChanged(new PropertyChangedEventArgs("MyProp"));
}
Here is the example project with more details, where I create user control with String property ValueTwo which split in two different TextBoxes using some custom logic, and combine value and update when user change the text.
And this is article which help me http://support.microsoft.com/kb/327413
Upvotes: 2