動作は今まで通り
です。
MainWindow.xaml
<Window x:Class="HelloWorld.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel> <Label Content="名前を入れてね" /> <TextBox Text="{Binding Name}" /> <Button Content="Enter" Click="ButtonEnter_Click" /> <TextBlock Text="{Binding Message}" /> </StackPanel> </Window>
MainWindow.xaml.cs
using System.Windows; namespace HelloWorld { ////// MainWindow /// public partial class MainWindow : Window { ////// ViewModel /// private MainViewModel _viewmodel; ////// Constructor /// public MainWindow() { InitializeComponent(); _viewmodel = new MainViewModel(); this.DataContext = _viewmodel; } ////// ボタン押下時のイベント処理 /// /// /// private void ButtonEnter_Click(object sender, RoutedEventArgs e) { _viewmodel.SetMessage(); } } }
MainViewModel.cs
using System; using System.Windows; using System.Windows.Input; namespace HelloWorld { ////// MainWindowのViewModel /// class MainViewModel : ViewModelBase { private string _Name; private string _Message; ////// Constructor /// public MainViewModel() { } #region Property ////// Name Property /// public string Name { get { return _Name; } set { if (_Name != value) { _Name = value; RaisePropertyChanged("Name"); } } } ////// Message Property /// public string Message { get { return _Message; } set { if (_Message != value) { _Message = value; RaisePropertyChanged("Message"); } } } #endregion ////// メッセージをセットする処理 /// public void SetMessage() { Message = "こんにちは、" + Name + "さん!"; } } }
ViewModelBase.cs
using System.ComponentModel; namespace HelloWorld { ////// ViewModelの基底クラス /// class ViewModelBase : INotifyPropertyChanged { ////// プロパティ変更のイベント /// public event PropertyChangedEventHandler PropertyChanged; ////// プロパティ変更のイベントを発行する /// /// internal void RaisePropertyChanged(string prop) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } } }
変わったところは、MainWindow.xaml.csのボタンのイベントハンドラの処理内容をViewModelに書いたことでしょうか。
イベントの受けはxaml.csでやっても、ビジネスロジックは、ViewModelに書きたい。というところがポイントです。
しっかし、ViewModelは長くなるなぁ。。。なんかいい方法ないかなぁ。
さぁて、次はどんなプログラムを作ろうかな。
0 件のコメント:
コメントを投稿