更改静态int变量时触发事件

本文关键字:事件 变量 静态 int | 更新日期: 2023-09-27 18:21:09

我现在正在用Silverlight 5编写一个网站。我设置了一个公共静态类,并在该类中定义了一个公用静态int。在MainPage类(它是一个公共分部类)中,我想在公共静态int更改时捕获一个事件。我有没有办法为自己举办一场活动,或者有没有其他方法可以让我做出同样的行为?(或者我想做的事情可能吗?)

更改静态int变量时触发事件

要详细说明Hans所说的内容,可以使用属性而不是字段

字段:

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

属性:

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

像使用常规字段一样使用属性。当对它们进行编码时,value关键字会自动传递给set访问器,它是变量被设置为的值

Foo.Bar = 100

将通过100,所以value将是100

属性本身不存储值,除非它们是自动实现的,在这种情况下,您将无法定义访问器(get和set)的主体。这就是我们使用私有变量bar来存储实际整数值的原因。

edit:实际上,msdn有一个更好的例子:

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