简体   繁体   English

在 Class 中实现 INotifyPropertyChanged

[英]Implement INotifyPropertyChanged in a Class

I created the 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));
        }
    }

Now when I try to use it in usercontrol现在当我尝试在用户控件中使用它时

public partial class myUserControl : UserControl, BindableBase

I encounter the following error我遇到以下错误

myUserControl can not have multiple base class myUserControl 不能有多个基数 class

INotifyPropertyChanged is intended for view model classes, not for the views (or user controls) themselves. INotifyPropertyChanged用于视图 model 类,而不是视图(或用户控件)本身。 Therefore you don't normally need them in the views.因此,视图中通常不需要它们。 You should use dependency properties instead, if you want to add fields to a user control.如果要将字段添加到用户控件,则应改为使用依赖属性。

See the example on UserControl :请参阅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); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM