开发者

DependencyProperty / INotifyPropertyChanged on low level objects

开发者 https://www.devze.com 2023-04-12 17:56 出处:网络
I have some fairly low level classes that are used in a WPF application that I\'m working on. One, for example represents an object that will be displayed as a list in a ScrollViewer and displayed wit

I have some fairly low level classes that are used in a WPF application that I'm working on. One, for example represents an object that will be displayed as a list in a ScrollViewer and displayed with a DataTemplate. The binding works great for the several properties that are used in the UI and I used this object purely because it was just convenient to pass up to the UI. The problem is that the UI does not get notified of data changes because it does not implement INotifyPropertyChanged or DependencyProperty.

The classes mentioned are intended to be part of a library that could be used totally independent of the UI, so I'm worried about cluttering it up with UI specific stuff (especially with INPC, that thing is a crazy amount of code for such a little thing).

What would generally be done in this case, 开发者_如何学JAVAclutter up the low level classes with UI cruft or make a wrapper class that is for the UI. Or is there another option?


For good separation I would create a class that wraps your library class. The wrapper would implement the INotifyPropertyChanged interface and expose public properties that fire the PropertyChanged event when updated. The wrapper would get and set the actual values from the wrapped class...

public class Internal
{
    public int MyProperty { get; set; }
}

public class WrapperForInternal : INotifyPropertyChanged
{
    public event PropertyChanged(object sender, PropertyChangedEventArgs e);

    private Internal _i;
    public WrapperForInternal(Internal i)
    {
        _i = i;
    }

    public int MyProperty
    {
        get { return _i.MyProperty; }
        set
        {
            _i.MyProperty = value;
            RaisePropertyChanged("MyProperty");
        }
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Alternatively you could derive from the Internal class and add the interface and an extra property that fires the event. But I would prefer the complete separation myself.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号