Mittwoch, 25. Dezember 2013

Optimizing the implementation of INotifyPropertyChanged using [CallerMemberName] in .Net 4.5 and above

Heard about it first time at the BASTA! in Darmstadt, Feb. 2013:
M.Steyer showed new options/freatures of the recent .Net Version. There was also an article in the Windows.developer Magazine by G.Biswanger about it, later. I will pick it up here, too:

The View:

<Window x:Class="WpfApplication1_BindBaseDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:project="clr-namespace:WpfApplication1_BindBaseDemo"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<project:MainWindowViewModel></project:MainWindowViewModel>
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding MyText}"></TextBlock>
</Grid>
</Window>

The ViewModel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApplication1_BindBaseDemo
{
  public class MainWindowViewModel : BindBase
  {
    private string myText;
    public string MyText
    {
      get { return myText; }
      set { SetProperty(ref myText,value); }
    }
    public MainWindowViewModel()
    {
      MyText = "Hello World";
    }
  }
}


The Class BindBase.cs using the new [CallerMemberName]:

using System;
using System.Collections.Generic;
using System.ComponentModel; // for INotifyPropertyChanged
using System.Linq;
using System.Runtime.CompilerServices; // for CallerMemberName
using System.Text;
using System.Threading.Tasks;
namespace WpfApplication1_BindBaseDemo
{
  public abstract class BindBase : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;
    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]String propertyName = null)
    {
      if (object.Equals(storage, value)) return false;
      storage = value;
      this.OnPropertyChanged(propertyName);
      return true;
    }
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      var eventHandler = this.PropertyChanged;
      if (eventHandler != null)
        eventHandler(this, new PropertyChangedEventArgs(propertyName));
    }
  }
}
Benefit from the best Windows Desktop app in the world and use Strokey.Net!

Keine Kommentare:

Kommentar posten