【问题标题】:Implement INotifyPropertyChanged in a Class在类中实现 INotifyPropertyChanged
【发布时间】:2021-06-29 22:11:45
【问题描述】:

我在一个类中创建了 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# wpf inotifypropertychanged


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-04
      • 2018-03-29
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 2014-06-02
      • 1970-01-01
      相关资源
      最近更新 更多