【问题标题】:Routed events and dependency properties .NET wrapper confusion路由事件和依赖属性 .NET 包装器混淆
【发布时间】:2023-03-20 07:20:01
【问题描述】:

我是 WPF 新手,对路由事件和依赖属性的包装语法感到困惑 我在许多来源中看到路由事件和依赖属性是这样包装的

// Routed Event
public event RoutedEventHandler Click
{
 add
 {
  base.AddHandler(ButtonBase.ClickEvent, value);
 }
 remove
 {
  base.RemoveHandler(ButtonBase.ClickEvent, value);
 }
}

// Dependency Property
public Thickness Margin
{
 set { SetValue(MarginProperty, value); }
 get { return (Thickness)GetValue(MarginProperty); }
}

我从未见过 C# 中的 add / remove / set / get 排序关键字。这些是作为关键字的 C# 语言的一部分吗?我从未体验过或使用过它们,因为我没有在 C# 中工作过,因为我是一名 C++ 程序员?如果不是关键字,那么如果它们不是 C# 的一部分,编译器将如何处理它们以及它们是如何工作的

【问题讨论】:

  • 这是 C# 语言的基础知识,相信你必须通读 MSDN 关于 .NET 的属性和事件
  • 同意@sil,这与(直接)WPF 无关。在查看 Routed/Dependency 变体之前,您应该了解“正常”属性和事件。

标签: c# wpf syntax dependency-properties routed-events


【解决方案1】:

我会试着为你总结一下:

依赖属性:

public int MyProperty
{
    get { return (int)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), new UIPropertyMetadata(MyDefaultValue));

这是完整的语法,你不必记住它,只需在 Visual Studio 中使用“propdp”sn-p。
“get”必须返回它引用的类型的值(在我的示例中为 int)。无论何时打电话

int MyVar = MyProperty;

“get”中的代码被求值。
该集合具有类似的机制,只是您有另一个关键字:“value”,它将是您分配给 MyVariable 的值:

MyProperty = 1;

将调用 MyProperty 的“set”,“value”将为“1”。

现在是 RoutedEvents:

在 C# 中(如在 C++ 中,如果我错了,请纠正我),订阅一个事件,你这样做

MyProperty.MyEvent += MyEventHandler;

这将调用“添加”-->您正在向堆栈添加处理程序。 现在,由于它不会自动进行垃圾回收,并且我们希望避免内存泄漏,所以我们这样做:

MyProperty.MyEvent -= MyEventHandler;

这样我们的对象就可以在我们不再需要时安全地处理掉。 这就是评估“删除”表达式的时间。

这些机制允许您在一个“get”上执行多项操作,WPF 中广泛使用的示例是:

private int m_MyProperty;
public int MyProperty
{
   get
   {
      return m_MyProperty;
   }
   set
   {
      if(m_MyProperty != value)
      {
         m_MyProperty = value;
         RaisePropertyChanged("MyProperty");
       }
    }
}

在实现 INotifyPropertyChanged 的​​ ViewModel 中,它将通知视图中的绑定属性已更改并且需要再次检索(因此它们将调用“get”)

【讨论】:

    猜你喜欢
    • 2013-09-25
    • 2017-01-31
    • 1970-01-01
    • 2017-10-20
    • 2021-06-29
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多