ケの日常

備忘録代わりのブログ

WPFのCommand書いてみる

とりあえずWPFでBindingでHello, World!表示するとこまではできたので
次はCommandで何かやってみた。

業務で使ってた時はもう基盤とかが出来上がってたから書くのそこまで大変じゃなかったイメージだけど
いざ一から書いてみるとなると何か書けばいいか全然思い出せなくて割とめんどい。

今後実際作ってみるときはちょっと工夫していかねば。

  • ViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace WpfSampleApp
{
    class SampleViewModel: INotifyPropertyChanged
    {

        public SampleViewModel() {

            this.Text = "Hello, World!";
            this.HelloCommand = new HelloCommand();
        }

        private string _text;
        public string Text
        {
            get
            {
                return _text;
            }
            set
            {
                _text = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Text"));
                }
            }
        }

        public ICommand HelloCommand { get; private set; }


        public event PropertyChangedEventHandler PropertyChanged;
    }

    class HelloCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            MessageBox.Show("Hello, World!");
        }
    }
}
  • View
<Window x:Class="WpfSampleApp.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:WpfSampleApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:SampleViewModel/>
    </Window.DataContext>    
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding Text}"/>
            <Button Command="{Binding HelloCommand}" 
                    HorizontalAlignment="Left"
                    Content="hello"
                    Height="30" 
                    Width="100" />
        </StackPanel>
    </Grid>
</Window>
  • 結果

f:id:NaN_Pole:20190529223939p:plain

もう少し楽していろいろ書けるようにしていきたい。