Ian*_*old 4 c# silverlight events event-handling
我现在正在Silverlight 5中编写一个网站。我建立了一个公共静态类,并且在该类中定义了一个公共静态int。在MainPage类(这是一个公共的局部类)中,我想捕获公共static int更改时的事件。有什么办法可以设置一个活动来为我做这件事,还是有另一种方式我可以得到相同的行为?(或者我正在尝试做的甚至有可能吗?)
要详细说明汉斯所说的话,可以使用属性代替字段
领域:
public static class Foo {
public static int Bar = 5;
}
Run Code Online (Sandbox Code Playgroud)
特性:
public static class Foo {
private static int bar = 5;
public static int Bar {
get {
return bar;
}
set {
bar = value;
//callback here
}
}
}
Run Code Online (Sandbox Code Playgroud)
就像常规字段一样使用属性。对它们进行编码时,value关键字会自动传递给set访问器,并且是将变量设置为的值。例如,
Foo.Bar = 100
会通过100,所以value会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));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
http://msdn.microsoft.com/en-us/library/ms743695.aspx
| 归档时间: |
|
| 查看次数: |
6002 次 |
| 最近记录: |