2

Newbie question.

I have two c# classes - a code class (say, CodeClass) and a form class (say, FormClass). In CodeClass I have a number of functions which I will use to periodically update a string within the class (I can use a property or whatever is appropriate). I want some way of notifying other classes when this string value changes. i.e., I'll try to have FormClass subscribe to change events on string message and then print the value to a text box or similar. However, at some point in the future, I need to provide API functions from CodeClass - so basically I need a way to notify any subscribing class of changes in the string message (string message does not get modified anywhere outside CodeClass - it happens within functions in CodeClass). I have tried with events and delegates etc but these all seem to be implemented by an external class modifying the string message (property).

Regards, etc

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
ftl25
  • 51
  • 1
  • 6
  • Side note, if you wish to do this to update Controls based on the propreties of an Object, there are DataBinding controls that does all of that for you without adding much code! – Alexandre Apr 03 '12 at 14:13

2 Answers2

5

You need to implement the INotifyPropertyChanged interface:

class CodeClass : INotifyPropertyChanged
{

    private string _myProperty;
    public string MyProperty
    {
        get { return _myProperty; }
        set
        {
            _myProperty = value;
            OnPropertyChanged("MyProperty");
        }
    }

    #region INotifyPropertyChanged implementation

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion

}

In FormClass, you can subscribe to the PropertyChanged event like this:

codeClass.PropertyChanged += codeClass_PropertyChanged;

...

void codeClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName = "MyProperty")
    {
        ...
    }
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

Just create an event, and fire that event when the string changes.

public class CodeClass
{
    private string _someString;
    public string SomeString 
    {
        get { return _someString; }
        set 
        {
            _someString = value;
            if (SomeStringChanged != null) { SomeStringChanged(value) }
        }
    }
    public event Action<string> SomeStringChanged;
}

Note: There is a standard way to do this, the INotifyPropertyChanged interface, as the other answer used. This is used primarily in WPF and Silverlight, but there's no reason you couldn't use it in Windows Forms.

Eric Andres
  • 3,417
  • 2
  • 24
  • 40