【问题标题】:How to define and raise an event inside a static method (a PropertyChangedCallback)如何在静态方法中定义和引发事件(PropertyChangedCallback)
【发布时间】:2019-02-20 15:23:07
【问题描述】:

我在名为 ValueChanged 的自定义控件 (Field) 中定义了一个事件。

public static event EventHandler<ValueChangedEventArgs> ValueChanged;

还有一个依赖属性Value

public string Value
{
    get => (string)GetValue(ValueProperty);
    set => SetValue(ValueProperty, value);
}

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register(nameof(Value), typeof(string), typeof(Field),
        new PropertyMetadata(OnValuePropertyChanged));

当这个值改变时我需要触发我的事件(如果FireValueChangedtrue)。

private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    bool fire = (bool)d.GetValue(FireValueChangedProperty);
    if (fire) ValueChanged?.Invoke(d, new ValueChangedEventArgs($"{e.NewValue}", $"{e.OldValue}"));
}

这是ValueChangedEventArgs

public class ValueChangedEventArgs : EventArgs
{
    public string NewValue { get; }
    public string OldValue { get; }
    //Other calculated properties...

    public ValueChangedEventArgs(string newValue, string oldValue)
    {
        NewValue = newValue;
        OldValue = oldValue;
    }
}

但在我的main window 中是这样说的

无法设置处理程序,因为该事件是静态事件。

当我尝试编译时,它会说

XML 命名空间“clr-namespace: ...”中不存在属性“ValueChanged”。

如果我尝试将事件设置为非静态,我无法在静态 OnValuePropertyChanged 方法中使用它。

【问题讨论】:

  • 旁注:使用和订阅static 事件时要非常小心。导致潜在内存泄漏的好方法。

标签: c# wpf xaml events custom-controls


【解决方案1】:

您可以像这样在OnValuePropertyChanged 方法中访问值已更改的控件(我已将控件类命名为MyControl):

private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    bool fire = (bool)d.GetValue(FireValueChangedProperty);
    var ctrl = (MyControl)d;
    if (fire) 
      ctrl.ValueChanged?.Invoke(d, new ValueChangedEventArgs($"{e.NewValue}", $"{e.OldValue}"));
}

然后您可以删除 static 并将事件更改为实例级别的事件:

public event EventHandler<ValueChangedEventArgs> ValueChanged;

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    相关资源
    最近更新 更多