Skip to content

Instantly share code, notes, and snippets.

@castaneai
Last active October 29, 2020 15:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save castaneai/f174b5d3c4668390bdd3 to your computer and use it in GitHub Desktop.
Save castaneai/f174b5d3c4668390bdd3 to your computer and use it in GitHub Desktop.
[C#, WPF] MVVMで簡単なアプリを作成

[C#, WPF] MVVMで簡単なアプリを作成

実行画面

実行画面

設計図

設計図

感想

  • INotifyPropertyChangedが面倒.プロパティの変化時に自動的に呼び出してほしい
  • ICommandが面倒.ボタンをおしたときに直接メソッドを呼び出させてほしい
<Window x:Class="MVVMTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:MVVMTest.ViewModel"
Title="MainWindow" Height="111" Width="205">
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Button Command="{Binding PushButtonCommand}" Content="これを押すと下の数字が1増える" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="170"/>
<TextBox HorizontalAlignment="Left" Margin="10,34,0,0" TextWrapping="Wrap" Text="{Binding Count}" Width="120" Height="23" VerticalAlignment="Top"/>
</Grid>
</Window>
using System.Windows;
namespace MVVMTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
using System.ComponentModel;
using System.Windows.Input;
namespace MVVMTest.ViewModel
{
public class MainWindowViewModel : INotifyPropertyChanged
{
public int Count
{
get
{
return _count;
}
set
{
_count = value;
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("Count"));
}
}
}
public ICommand PushButtonCommand
{
get
{
if (_pushButtonCommand == null) {
_pushButtonCommand = new PushButtonCommand(this);
}
return _pushButtonCommand;
}
}
private int _count;
private ICommand _pushButtonCommand;
public event PropertyChangedEventHandler PropertyChanged;
}
}
using System;
using System.Windows.Input;
namespace MVVMTest
{
class PushButtonCommand : ICommand
{
private readonly ViewModel.MainWindowViewModel _viewModel;
public PushButtonCommand(ViewModel.MainWindowViewModel viewModel)
{
_viewModel = viewModel;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_viewModel.Count++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment