How can i RaisePropertyChanged on property change?

青春壹個敷衍的年華 提交于 2019-11-29 11:08:16

PropertyChanged is used to notify the UI that something has been changed in the Model. Since you're changing an inner property of the User object - the User property itself is not changed and therefore the PropertyChanged event isn't raised.

Second - your Model should implement the INotifyPropertyChanged interface. - In other words make sure UserAccount implements INotifyPropertyChanged, otherwise changing the firstname will not affect the view either.

Another thing:

The parameter RaisePropertyChanged should receive is the Name of the property that has changed. So in your case:

Change:
RaisePropertyChanged(String.Empty);

To
RaisePropertyChanged("User");

From MSDN:

The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.

(No need to refresh all the Properties in this case)

You can read more on the concept of PropertyChanged here

You can invoke a property changed event from another class. Not particularly useful if you have all the sources. For closed source it might be. Though I wouldn't consider it experimental and not production ready.

See this console copy paste example:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    public class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            a.PropertyChanged += A_PropertyChanged;
            var excpl = new Excpl();
            excpl.Victim = a;
            excpl.Ghost.Do();
        }

        private static void A_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Console.WriteLine("Event triggered");
        }
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct Excpl
    {
        [FieldOffset(0)]
        public A Victim;
        [FieldOffset(0)]
        public C Ghost;
    }

    public class A : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class C : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void Do()
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(""));
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!