#やること
- ViewModelフォルダの追加
- MainViewModelの追加
- MainWindow.xamlにnamespaceのエイリアス追加
- <Window.DataContext>タグを追加
- 確認用にTitleをバインド
- Commandバインディング確認用にボタンを追加
#コード
MainWindow.xaml
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication4"
xmlns:vm="clr-namespace:WpfApplication4.ViewModel"
mc:Ignorable="d"
Title="{Binding Title}" Height="350" Width="525">
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<Button x:Name="button" Content="Button" Height="30" Width="75" Command="{Binding TestCommand}"/>
</Grid>
</Window>
MainViewModel.cs
namespace WpfApplication4.ViewModel
{
public class MainViewModel
{
public string Title { get { return "Hoge"; } }
public WpfCommand TestCommand { get; private set; }
public MainViewModel()
{
TestCommand = new WpfCommand(new Action(() =>
{
MessageBox.Show("ほげほげ");
}));
}
public class WpfCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private Action act;
public WpfCommand(Action act)
{
this.act = act;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
act();
}
}
}
}