C# 更改静态int变量时触发事件?
我正在用Silverlight 5写一个网站。我设置了一个公共静态类,在该类中定义了一个公共静态int。在MainPage类(这是一个公共部分类)中,我想在公共静态int发生更改时捕获一个事件。有没有什么方法可以让我举办一个活动来为自己做到这一点,或者有没有其他方法可以让我获得同样的行为?(或者我想做的事情可能吗?要详细说明Hans说的话,可以使用属性而不是字段 字段:C# 更改静态int变量时触发事件?,c#,silverlight,events,event-handling,C#,Silverlight,Events,Event Handling,我正在用Silverlight 5写一个网站。我设置了一个公共静态类,在该类中定义了一个公共静态int。在MainPage类(这是一个公共部分类)中,我想在公共静态int发生更改时捕获一个事件。有没有什么方法可以让我举办一个活动来为自己做到这一点,或者有没有其他方法可以让我获得同样的行为?(或者我想做的事情可能吗?要详细说明Hans说的话,可以使用属性而不是字段 字段: public static class Foo { public static int Bar = 5; } 特性:
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
}
}
}
像使用常规字段一样使用属性。对其进行编码时,值
关键字会自动传递给set访问器,并且是变量设置的值。比如说,
Foo.Bar=100
将通过100
,因此值将是100
属性本身不存储值,除非它们是自动实现的,在这种情况下,您将无法为访问器(get和set)定义主体。这就是为什么我们使用一个私有变量,bar
,来存储实际的整数值
编辑:实际上,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));
}
}
}
}
将其改为公共静态属性。现在很简单。使用静态事件时要小心内存泄漏(如果使用默认实现,只要不分离侦听器对象,它们就不会被垃圾收集)!谢谢为了实现这一点,我只需设置:Foo.PropertyChanged+=newpropertychangedventhadler(Foo_PropertyChanged);在主页上,一切都很好。不过,我需要将OnPropertyChanged更改为公共静态无效,就是这样!