首页 > 解决方案 > 在类中实现 INotifyPropertyChanged

问题描述

我在一个类中创建了 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 不能有多个基类

标签: c#wpfinotifypropertychanged

解决方案


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); }
}

推荐阅读