1ヶ月以上の開いてしまいました。
今回は、前回の Livet を使った簡単な MVVM のサンプルを作りたいと思います。
機能は TextBox に入力した文字列を別の TextBox にコピーするだけ。
とても、シンプルです。
画面はこんな感じ。(UI のセンスがありません)
では、はじめます。
Visual Studio Express 2013 を立ち上げたら、「Livet WPF4.5 MVVM アプリケーション」を選んでプロジェクトを作成します。
MainWindowVIewModel.cs を開いてたら、TextBox 用のプロパティを2つ追加します。
private string inputText;
public string InputText
{
get { return this.inputText; }
set
{
if (value != this.inputText)
{
this.inputText = value;
this.RaisePropertyChanged(() => this.InputText);
}
}
}
private string outputText;
public string OutputText
{
get { return this.outputText; }
private set
{
if (value != this.outputText)
{
this.outputText = value;
this.RaisePropertyChanged(() => this.outputText);
}
}
}
次にコピーの処理を追加します。
private void CopyAction()
{
this.OutputText = this.InputText;
}
最後にボタン用のコマンドを追加します。
private ViewModelCommand copyCommand;
public ViewModelCommand CopyCommand
{
get
{
return this.copyCommand = this.copyCommand ??
new ViewModelCommand(this.CopyAction);
}
}
MainWindow.xaml を開いてコントロールを追加します。
<Window x:Class="Kaznagamine.LivetSample.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:l="http://schemas.livet-mvvm.net/2011/wpf"
xmlns:v="clr-namespace:Kaznagamine.LivetSample.Views"
xmlns:vm="clr-namespace:Kaznagamine.LivetSample.ViewModels"
Title="MainWindow" Height="300" Width="400">
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=InputText}"
Width="120"
Height="23"
Margin="3"
TextAlignment="Right" />
<Button Command="{Binding Path=CopyCommand}"
Width="75"
Height="24"
Margin="3"
HorizontalAlignment="Right"
Content="コピー" />
<TextBox Text="{Binding Path=OutputText}"
Width="120"
Height="23"
Margin="3"
TextAlignment="Right"
IsReadOnly="True"/>
</StackPanel>
</Grid>
</Window>
ビルドして実行したら、左の TextBox に文字列を入力してボタンを押します。
右の TextBox に同じ文字列が表示されたら完成です。
頑張りすぎず脱力系でいこうと思います。
以上。
0 件のコメント:
コメントを投稿