Binding to my property??? How???

  • Thread starter Thread starter Vlatko
  • Start date Start date
V

Vlatko

I would like to write a class that has property, for example, MyText and I
want to be able to bind a Text property of a TextBox to my MyText property.
When I change the value of MyText property in my class that change should be
visible in binded control. How can I do this?

Thx.

P.S. This is just an example. I'm trying to make a property to witch I could
bind other visible components. Like when I bind Text property of textbox1 to
Text property of textbox2, and when I type something in textbox2 it appears
in textbox1. I hope I was clear enough what I'm trying to do. Thx again.
 
I would like to write a class that has property, for example, MyText and
I want to be able to bind a Text property of a TextBox to my MyText
property. When I change the value of MyText property in my class that
change should be visible in binded control. How can I do this?

Just create a class with a property MyText and bind it to the
textbox as:

myTextBox.DataBindings.Add("Text", myObjectToBind, "MyText");

To be sure that changes are propagated, you have to define the
event MyTextChanged in the class with the property MyText as well. This
event can be a simple event:

public event EventHandler MyTextChanged;

Then when the value MyText should return changes, you simply raise
that event when there are subscribers:

private string _myText;

public event EventHandler MyTextChanged;

//..

public string MyText
{
get { return _myText; }
set
{
_myText=value;
if(MyTextChanged!=null)
{
MyTextChanged(this, New EventArgs());
}
}
}

the datbinding logic in the controls will bind to the Changed event if
they're binded to a property with the same name. When the event is fired,
they'll refresh themselves with the new value.

FB
 
Frans,
the datbinding logic in the controls will bind to the Changed event if
they're binded to a property with the same name. When the event is fired,
they'll refresh themselves with the new value.


Is this property/event name convention described somewhere in MSDN? In other
words, can one safely rely on this naming scheme as an "official" one?
 
Frans,



Is this property/event name convention described somewhere in MSDN? In
other words, can one safely rely on this naming scheme as an "official"
one?

Unfortunately, it's the official one :) You're looking for 'simple
databinding'. You can find examples of that in the MSDN or online at the
MSDN site.

I say 'unfortunately' because if you have 20 properties, you have
to add 20 events, while it would have been better if there was just 1
event which had the property descriptor of the property that was changed.
That way it would be more flexible. Ah well. :)

FB
 
Back
Top