LoginSignup
4
1

MVVMで、INotifyPropertyChangedを簡潔に使う。コードスニペット付き。

Last updated at Posted at 2023-12-05

MVVMではプロパティを大量に使うことが多いです。
そうした時、INotifyPropertyChangedを、楽して使いたいですよね。
私は、次のようにしています。

INotifyPropertyChangedをできる限りコードを減らして利用

抽象クラスを準備します。

そして、
Implementing INotifyPropertyChanged - does a better way exist?
の回答である、
https://stackoverflow.com/a/1316417
のコードを利用します。

C# 8 で、 Nullable reference typesの場合は、次の通りです。

/// <summary>
/// https://stackoverflow.com/a/1316417
/// </summary>
public abstract class NotifyBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}

次のようにNotifyBaseを継承して利用します。

public class MainModel : NotifyBase
{
    private int _no;
    public int No
    {
        get => _no;
        set => SetField(ref _no, value);
    }

    public MainModel()
    {
    }
}

コードスニペットの使い方

propmと入力すると、次が表示されます。

20231205 132654 Anonymous.png

バッキング フィールド名を変更します(標準的な命名では小文字ではじめる)。すると、プロパティ名も変更されます。
Tabキーで移動が便利。
20231205 132721 Anonymous.png

プロパティ名が小文字から始まるので大文字にします。
20231205 132917 Anonymous.png

Visual Studio用 スニペット

バッキングフィールドとプロパティを作成するための、スニペット用コードです。

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propm</Title>
            <Shortcut>propm</Shortcut>
            <Description>プロパティとバッキング フィールド用のコード スニペット</Description>
            <Author>mikihiro</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>プロパティ型</ToolTip>
                    <Default>string</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>プロパティ名</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
                </Declarations>
            <Code Language="csharp"><![CDATA[
      
  private $type$ _$property$;
  public $type$ $property$
  {
      get => _$property$;
      set => SetField(ref _$property$, value);
  }
  $end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
4
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1