简体   繁体   中英

Trigger event when static int variable is changed?

I'm writing a website in Silverlight 5 right now. I have a public static class set up, and in that class I have a public static int defined. In the MainPage class (which is a public partial class), I want to capture an event when the public static int is changed. Is there any way I could set up an event to do this for me, or is there another way I would be able to get the same behaviour? (Or is what I am trying to do even possible?)

To elaborate on what Hans said, you can use properties instead of fields

Fields:

public static class Foo {
    public static int Bar = 5;
}

Properties:

public static class Foo {
    private static int bar = 5;
    public static int Bar {
        get {
            return bar;
        }
        set {
            bar = value;
            //callback here
        }
    }
}

Use properties just as you would regular fields. When coding them, the value keyword is automatically passed to the set accessor and is the value the variable is being set to. For example,

Foo.Bar = 100

Would pass 100 , so value would be 100 .

Properties on their own do not store values unless they are auto-implemented, in which case you wouldn't be able to define a body for the accessors (get and set). This is why we use a private variable, bar , to store the actual integer value.

edit : Actually, msdn has a much nicer example:

using System.ComponentModel;

namespace SDKSample
{
  // This class implements INotifyPropertyChanged
  // to support one-way and two-way bindings
  // (such that the UI element updates when the source
  // has been changed dynamically)
  public class Person : INotifyPropertyChanged
  {
      private string name;
      // Declare the event
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }

      public Person(string value)
      {
          this.name = value;
      }

      public string PersonName
      {
          get { return name; }
          set
          {
              name = value;
              // Call OnPropertyChanged whenever the property is updated
              OnPropertyChanged("PersonName");
          }
      }

      // Create the OnPropertyChanged method to raise the event
      protected void OnPropertyChanged(string name)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(name));
          }
      }
  }
}

http://msdn.microsoft.com/en-us/library/ms743695.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM