LoginSignup
3
6

More than 5 years have passed since last update.

WPFの画面を追加した後にやっておくこと

Last updated at Posted at 2016-05-31

やること

  • ViewModelフォルダの追加
  • MainViewModelの追加
  • MainWindow.xamlにnamespaceのエイリアス追加
  • <Window.DataContext>タグを追加
  • 確認用にTitleをバインド
  • Commandバインディング確認用にボタンを追加

プロジェクト構成

image

コード

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

実行

ウィンドウのタイトルがHogeになればおk
image

ボタンクリックでメッセージボックス表示
image

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6