简体   繁体   中英

WPF: Best way to block OnPropertyChanged

I have implemented WPF data binding with INotifyPropertyChanged.

  public class ExportNode : INotifyPropertyChanged
{
    public uint Handle { get; set; }
    public String Text { get; set; }
    private bool _ischecked;
    public bool IsChecked
    {
        get
        {
            return _ischecked;
        }
        set
        {
            _ischecked = value;
            OnPropertyChanged("IsChecked");

        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    // Create the OnPropertyChanged method to raise the event 
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        } 
    }
}

And than subscribing to event form my code, so whenever I change property in UI, it fires callback. But now I'm trying to figure out the best way to change property from code, and than not fire callback, just update UI.

        void newNode_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
           if (e.PropertyName == "IsChecked")
           {
           }
        }

For now I just thought about implementing some "blocker" member property in ExportNode

        protected void OnPropertyChanged(string name)
    {
        if (Blocked)
            return;
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        } 
    }

or delete event form instance before change.

                newNode.PropertyChanged -= newNode_PropertyChanged;
                newNode.IsChecked = true;
                newNode.PropertyChanged += newNode_PropertyChanged;

But is there any better way? I just don't understand some basics? :-)

Thank you very much

Roman

You've got this a little backwards.

INotifyPropertyChanged , and thus the PropertyChanged event, is what makes the UI update, in fact, its what makes the whole binding system work.

So to update the UI, you have to raise that event. Now, from the code side, you almost never subscribe to that event, because you could just invoke a method from the setter. Something like:

    set
    {
        _ischecked = value;
        OnPropertyChanged("IsChecked");

        if (!Blocked)
            MyOtherMethod();
    }

Note that if you are dealing with threads, that Blocked condition is a major synchronization hazard.

If you really need to register for PropertyChanged from code, then your best bet is to just unregister with -= . That way the UI still gets its event, but you don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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