如何在静态方法(PropertyChangedCallback)中定义和引发事件

How to define and raise an event inside a static method (a PropertyChangedCallback)

我在名为 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}"));
}

这是ValueChangedEventArgsclass

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中它说

cannot set the handler because the event is a static event.

当我尝试编译时它说

the property 'ValueChanged' does not exist in the XML namespace 'clr-namespace: ...'.

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

您可以像这样在 OnValuePropertyChanged 方法中访问值已更改的控件(我已将控件命名为 class 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;