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}");
}