在 Class 中实施 INotifyPropertyChanged

Implement INotifyPropertyChanged in a Class

我在 class

中创建了 INotifyPropertyChanged
public class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return;
            }

            storage = value;
            RaisePropertyChanged(propertyName);
        }

        protected void RaisePropertyChanged([CallerMemberName]string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

现在当我尝试在用户控件中使用它时

public partial class myUserControl : UserControl, BindableBase

我遇到以下错误

myUserControl can not have multiple base class

INotifyPropertyChanged 适用于视图模型 类,不适用于视图(或用户控件)本身。因此,您通常不需要在视图中使用它们。如果要向用户控件添加字段,则应改用依赖属性。

参见 UserControl 上的示例:

/// <summary>
/// Identifies the Value dependency property.
/// </summary>
public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register(
        "Value", typeof(decimal), typeof(NumericUpDown),
        new FrameworkPropertyMetadata(MinValue, new PropertyChangedCallback(OnValueChanged),
                                      new CoerceValueCallback(CoerceValue)));

/// <summary>
/// Gets or sets the value assigned to the control.
/// </summary>
public decimal Value
{          
    get { return (decimal)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}