C# 5–Making INotifyPropertyChanged Easier

There are times when I think my friends in the C# team are just listening to me gripe before adding a cool new feature that solves the problem.  (I have never quite outgrown the assumption that the world revolves around me).

A couple years ago I grew really tired of having to create the same old same old when it came to public properties,

private int _myValue;
public int MyValue
{
  get { return _myValue; }
  set { _myValue = value; }
}

 

No sooner did I whine about this, then along came automatic properties and life became much easier.  The above boiled down to

private int MyValue { get; set; }

 

My new gripe (and yours, no doubt) was the work involved in sending in the name of the calling property for INotifyPropertyChanged.  It became common practice to write a helper method that took the name of the property and fed it to the PropertyChanged event, but it was a string being passed around and one tiny typo and your property did not update the UI.  Here’s the old way…

 

private string _name;

public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        RaisePropertyChanged("Name");
    }
}

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

 

Notice that the Name property has to send “Name” to the RaisePropertyChanged helper method. 

With C# 5, this problem is solved (Hoot!) by adding an attribute to the argument in RaisePropertyChanged:  [CallerMemberName]  The new syntax, which is much less error prone is:

private string _name;

public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        RaisePropertyChanged();
    }
}

private void RaisePropertyChanged(
    [CallerMemberName] string caller = "" )
{
  if (PropertyChanged != null)
  {
    PropertyChanged( this, new PropertyChangedEventArgs( caller ) );
  }
}

 

Notice that you no longer include the name of the property when calling RaisePropertyChanged.  You just call it, and due to the attribute, the called method figures out what the caller member name is and places that into the string parameter.  Sweet.

Here’s the complete C# for the Employee class for Win 8, followed by the XAML to test it on Win 8…

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace PropertyChanged
{
    class Employee : INotifyPropertyChanged
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged();
            }
        }

        public void SetName( string newName )
        {
            Name = newName;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged( [CallerMemberName] string caller = "")
        {
            if ( PropertyChanged != null )
            {
                PropertyChanged( this, new PropertyChangedEventArgs( caller ) );
            }
        }
    }
}

 

The XAML…

<Page
    x:Class="PropertyChanged.MainPage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PropertyChanged"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Orientation="Horizontal">
        <TextBlock
            Name="NameDisplay"
            Text="{Binding Name}" />
            <Button
                Height="100"
                Width="200"
                Content="Change name"
                Name="ChangeName"
                Click="ChangeName_Click_1" />
        </StackPanel>
    </Grid>
</Page>

 

The code-behind…

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


namespace PropertyChanged
{

    public sealed partial class MainPage : Page
    {

        Employee emp = new Employee();

        public MainPage()
        {
            this.InitializeComponent();
        }

       
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            DataContext = emp;
            emp.SetName( "Joe" );
        }

        private void ChangeName_Click_1( object sender, RoutedEventArgs e )
        {
            emp.SetName( "Bob" );
        }
    }
}

Unknown's avatar

About Jesse Liberty

** Note ** Jesse is currently looking for a new position. You can learn more about him at https://jesseliberty.bio Thank you. Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 13 year Microsoft MVP.
This entry was posted in Essentials, Languages, Windows 8 and tagged . Bookmark the permalink.

77 Responses to C# 5–Making INotifyPropertyChanged Easier

  1. Jason's avatar Jason says:

    Does PropertyChanged.Fody obviate the need for this? https://github.com/Fody/PropertyChanged

  2. Stacysen's avatar Stacysen says:

    Если вы хотите узнать как заработать в в глобальной сети интернета или как раскрутитьпривлечь людей на свой сайт, то стоит посетитьприйти на наш портал.
    Здесь вы узнаете не только о практический всех популярных безопасных видах заработка, но и сможете скачать софт для продвижение бизнеса, партнерки, блога или сайта.
    У нас предоставленны такие программы как:
    -AVTOREG-VK-автозаполнение аккаунтов
    -Forum Poster-постинг на форумы
    -Apbotod-раскрутка группы в Одноклассниках
    -Apbotod-лучшаянадежная и эффективная программа для авторазмещение объявлений на Avito
    -XSpamer-авторассылка электронных писем
    -VkBot 2.0-комплексное профессиональное продвижение Вконтакте
    И многие другие полезные программы для вебмастеров и людей у которых имеется свой бизнесс в интернете.
    Для новичков имеется много полезной настоящей и полезной информации о том как и на чем можно заработать в интернете.

    заработок в интернете как заработать в интернете

  3. Steve's avatar Steve says:

    Do you happen to have an example that uses a TimePicker? I’m trying to implement a solution where the background color of the field is set to red if a start time is set through a picker that is later than the end time. We have a DateSelected public event for a DatePicker, but do we have a TimeSelected event for a TimePicker, of course not. So we have to implement it via the property changed event. I can’t seem to get the event handler to respond even though I use RaisePropertyChanged() on the property within the ViewModel.

  4. Jorge's avatar Jorge says:

    Hi Jesse,

    Thanks for your job, i have a question, how to use inotifyproperty change in an object

    for exmaple:
    I have a simple class,

    public class Employe:INotifyPropertyChanged
    {
    public string Name {get; set;}
    public string Surname {get; set}
    }

    And i have a viewmodel class
    public class viewModel:InotifyPropertyChange
    {
    private Employe_employe;

    public Employe Employe
    {
    get { return _employe; }
    set
    {
    _employe= value;
    RaisePropertyChanged();
    }
    }

    private void RaisePropertyChanged(
    [CallerMemberName] string caller = “” )
    {
    if (PropertyChanged != null)
    {
    PropertyChanged( this, new PropertyChangedEventArgs( caller ) );
    }
    }

    }
    And the xaml

    ¿I’m absolutely wrong or can be done? ¿how please?
    Thank you very much!

  5. game's avatar game says:

    Appreciate this post. ʟet me trry it οut.

  6. Wow, this paragraph iѕ pleasant, mу sister is analyzing tɦese things, tɦerefore Ι am going to
    let know her.

  7. Unknown's avatar Anonymous says:

    It hangs in Firefox too with an error that the javascript times out and the option to wait, cancel or debug…

  8. Unknown's avatar Anonymous says:

    This page hangs in Safari and Chrome!

  9. Your style is so unique in comparison to
    other folkks I’ve rdad stuff from. Many thanks for
    posting when you have tthe opportunity, Guess I will just book mark this page.

    Feeel free too visit my webpage; offering; scatter.dpi.me,

  10. Here in this portal you will get all information regarding 2015 exam results,
    jee main answer key 2015, jee main reuslt, cbse 10th result, cbse 12th results
    2015, entrance exam, viteee, srmeee.

  11. Unknown's avatar Anonymous says:

    I have been waiting for the same thing for years 🙂

  12. I know this if off topic but I’m looking into starting
    my own blog and was curious what all is needed to get setup?
    I’m assuming having a blog like yours would cost a pretty
    penny? I’m not very internet smart so I’m not 100% certain. Any tips
    or advice would be greatly appreciated. Kudos

    my web site computer technician

  13. korta.st's avatar korta.st says:

    Pretty! This has been an extremely wonderful article.
    Thank you forr supplying these details.

  14. Fine way of describing, and good paragraph to take data regarding my presentation focus, which i am going
    to present in institution of higher education.

    Stop by my web page – quick unsecured loans

  15. I’ve read some just right stuff here. Certainly value bookmarking for revisiting.

    I wonder how so much effort you place to make this type
    of wonderful informative site.

    Look at my webpage Odzież reklamowa efektywną reklamą

  16. I do not even know how I stopped up here, however
    I thought this post was good. I don’t recognise who you are but certainly you’re going to a well-known blogger if you are not already.
    Cheers!

    Feel free to visit my webpage … benefiance concentrated anti-wrinkle eye cream

  17. Definitely believe that which you stated. Your favourite reason appeared to be on the web the simplest thing to take note of.
    I say to you, I definitely get irked even as folks consider
    concerns that they just do not know about. You managed to hit the nail upon the
    highest as well as defined out the entire thing with
    no need side effect , folks could take a signal.
    Will probably be again to get more. Thanks

  18. If some one desires expert view regarding blogging then i propose him/her
    to go to see this web site, Keep up the pleasant work.

    Stop by my web blog … karatbars international compensation

  19. It’s very trouble-free to find out any topic on net as compared to books,
    as I found this post at this website.

  20. I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored subject matter stylish.

    nonetheless, you command get got an edginess over that you wish be delivering the following.
    unwell unquestionably come further formerly again as
    exactly the same nearly a lot often inside case you shield this
    hike.

    Here is my webpage affiliate marketing programs for beginners

  21. youtube.com's avatar youtube.com says:

    Thank you for the auspicious writeup. It if truth be told was a amusement account it.
    Glance advanced to more brought agreeable from you!
    By the way, how can we be in contact?

  22. Best Place To Buy youth Nets jersey

  23. A perfect decorating cork will well suit the kid’s room, the children are too rough and handle things in a very
    arrogant way, the kids will bounce the ball on the walls or will throw
    up heavy stuffs on the walls, or they will also scribble their favorite quotes or slogans or animate their favorite
    cartoon character. When you have to make basically the right feel for your inward part space, whether it is a
    striking choice for the room or an enchanting and master feel
    in an office, the masters are the specific authorities
    to call. The process of residential painting is not the most fun activity to perform,
    but if you make it enjoyable by doing it with a friend and good music, interior painting, as well as that of the exterior of your
    home, can be a more pleasant experience.

  24. Thinking about the job at hand, and if you realize that you
    just don’t have the skills or the time to do the job right, then you may want
    to consider hiring a painting contractor to come in and paint your home for you.
    In the event you drive with a house that has a sign proclaiming what house painting company is
    working as well as has worked on a house, this is the sign how
    the homeowner can be harpy with the function and is happy to let the business have some no cost advertizing.
    Painting a house is usually only done once every 7
    years; with enough time and effort dedicated to painting your house, you will be absolutely satisfied with it until
    the next time that you decide to paint.

  25. Victims in an automobile accident commonly include motorists,
    passengers, pedestrians, and even the particular spouse of an injured
    individual that was not in the actual accident but is a victim suffering loss.
    If a staff member might have been provided with personal protective tools but is
    unable to put on it, and they then come into contact with moving machines,
    their workplace is going to be considered to get behaved negligently
    by failing to defend risky device components.
    The reason for this is due to the fact that they have gone to court for personal injury settlements before concerning other people, so you are working with someone who
    knows how to handle this type of case.

  26. vms signs's avatar vms signs says:

    Hi there to all, hhow is the whole thing, I think every
    one is gettiing more from this website, and your views arre nice
    desiggned for new users.

Comments are closed.