0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【忘備録】WPFでMVVMやるときのサンプルテンプレート集

Posted at

WPFアプリをMVVMで開発する際によく使うコードのテンプレートをここに残しておく。

コマンドクラス

RelayCommand.cs
using System;
using System.Windows.Input;

namespace ListViewLib
{
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter) => _canExecute?.Invoke(parameter) ?? true;
        public void Execute(object parameter) => _execute(parameter);

        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }
}

INotifyPropertyChangedの実装

sample.cs
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName) =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

VMのプロパティ

sampleViewModel.cs
        private string _property;
        public string Property
        {
            get => _property;
            set
            {
                if (_property == value) return;
                _property = value;
                OnPropertyChanged(nameof(Property));
            }
        }

DependancyProperty

SampleDependancyProperty.cs
        static public DependencyProperty SampleProperty =
            DependencyProperty.Register(
            nameof(Sample),
            typeof(string),
            typeof(SampleDependancyProperty),
            new PropertyMetadata(null, SamplePropertyChanged));

        public string Sample
        {
            get => (string)GetValue(SampleProperty);
            set => SetValue(SampleProperty, value);
        }
        private static void SamplePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            Trace.WriteLine($"Sampleが変わりました。NewValue={e.NewValue}");
        }
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?