「 ViewModelCommand 知ってないと 詰む……」
📖 wpf-view-model-command-practice - Git hub に上げたもの
「 👆 プロジェクト作成後、速攻 Livetを NuGet でインストール」
「 👆 Views
と ViewModels
フォルダーを作れだぜ」
「 👆 MainWindow.xaml
を Views
フォルダーの下に移動しろだぜ。
それとともに MainWindow.xaml
の冒頭の x:Class=""
のとこのパスに .Views
を足しとけだぜ」
「 👆 MainWindow.xaml.cs
の方も namespaceに .Views
を足しとけだぜ」
「 👆 App.xaml
の StartupUri の方も Views/
を足しとけだぜ」
namespace WpfViewModelCommandPractice.ViewModels
{
using Livet.Commands;
using System;
public class MainWindowModel
{
private ViewModelCommand _calledHello;
/// <summary>
/// ハローと表示するコマンド
/// </summary>
public ViewModelCommand CalledHello
{
get
{
if (_calledHello == null)
{
_calledHello = new ViewModelCommand(Hello);
}
return _calledHello;
}
}
/// <summary>
/// ハローと表示します
/// </summary>
public void Hello()
{
Console.WriteLine("Hello, world!!");
}
}
}
「 👆 ViewModel の方は こんな感じでクラスを作れだぜ。
ViewModelCommand のコンストラクタが メソッドを受け取れるのが分かるな」
<Window x:Class="WpfViewModelCommandPractice.Views.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:WpfViewModelCommandPractice"
xmlns:viewModels="clr-namespace:WpfViewModelCommandPractice.ViewModels"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<!-- ViewModel を、Windowに紐づけます -->
<Window.DataContext>
<viewModels:MainWindowModel/>
</Window.DataContext>
<Grid>
<Button Width="100" Height="100"
Content="ハロー"
Command="{Binding CalledHello}"/>
</Grid>
</Window>
「 👆 そして ビューの方のデザインは こんな感じ……、あれ? ボタンが機能しね?」
「 Console.WriteLine(...) が働いてないのかだぜ?」
namespace WpfViewModelCommandPractice.ViewModels
{
using Livet.Commands;
using System;
using System.Diagnostics;
public class MainWindowModel
{
private ViewModelCommand _calledHello;
/// <summary>
/// ハローと表示するコマンド
/// </summary>
public ViewModelCommand CalledHello
{
get
{
if (_calledHello == null)
{
_calledHello = new ViewModelCommand(Hello);
}
return _calledHello;
}
}
/// <summary>
/// ハローと表示します
/// </summary>
public void Hello()
{
// Console.WriteLine("Hello, world!!"); // デバッグ中は働かなかった
Trace.WriteLine("Hello, world!!"); // デバッグ中に働いた
}
}
}
「 👆 Console を Trace に変えたら 動いたぜ。デバッグで動きを確認するだけなんで これで十分だぜ」
「 これで View から、 ViewModel にあるメソッドを呼び出す指示を書けたな」
Crieitは個人で開発中です。
興味がある方は是非記事の投稿をお願いします! どんな軽い内容でも嬉しいです。
なぜCrieitを作ろうと思ったか
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください!