以前的.NET中是否提供此功能

时间:2012-01-15 19:05:07

标签: .net wpf delegates callback dependency-properties

我正在查看Charles Petzold中的一些代码,他使用PropertyChangedCallback

的以下语法
public static readonly DependencyProperty CenterProperty =
  EllipseGeometry.CenterProperty.AddOwner(
    typeof(CenteredEllipse),
    new FrameworkPropertyMetadata(new Point(0, 0), 
      EllipsePropertyChanged));

如果你这样做,你需要将属性更改回调放在新new PropertyChangedCallback(EllipsePropertyChanged)中,它不起作用。他也在直接编辑变量:

 void EllipsePropertyChanged(DependencyPropertyChangedEventArgs args)
{
  elipGeo.Center = Center;
  elipGeo.RadiusX = RadiusX;
  elipGeo.RadiusY = RadiusY;
  InvalidateMeasure();
}

应该是这样的:

static void EllipsePropertyChnaged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        EllipseGoemetry ellipseGeo = (EllipseGoemetry )obj;
        args.newValue ...
    }

有人知道发生了什么事吗?

3 个答案:

答案 0 :(得分:1)

第一个是委托类型推断的示例。由此:http://blogs.msdn.com/b/noahc/archive/2008/09/23/delegate-type-inference-in-c.aspx

  

直到今天我才知道的是第13行会起作用   可以只传递方法名称作为参数和委托类型   将被推断。好,易于。第14行/第15行对我来说也是新手,   至少关于使用()表示空参数列表的部分。

答案 1 :(得分:1)

elipGeo被定义为类的一个字段,该代码是正确的。

您不需要明确地从方法创建委托,这是隐式完成的,在C#2.0中添加了this feature

答案 2 :(得分:1)

问题是他对两种方法使用相同的名称,因此可能会让人感到困惑:

static void EllipsePropertyChanged(DependencyObject obj,
  DependencyPropertyChangedEventArgs args)
{
  (obj as CenteredEllipse).EllipsePropertyChanged(args);
}

void EllipsePropertyChanged(DependencyPropertyChangedEventArgs args)
{
  elipGeo.Center = Center;
  elipGeo.RadiusX = RadiusX;
  elipGeo.RadiusY = RadiusY;
  InvalidateMeasure();
}

第一个是委托,第二个只是一个类的方法,他在委托中调用,在那里他施放obj,就像它应该完成的那样。