WPFでなにか作ってみようということで差し当たり「Hello, World!」表示だけでもやってみる。
いつもWPF触ってみようと思ったときにViewModelってどうやって作ればいいんだっけ・・・?と
なってしまうので今日はまずとっかかりのようなもの。
本当にただ表示するぐらいしかしてなくて他にも必要な実装はあると思うけどとりあえず。
- ViewModel
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfSampleApp { class SampleViewModel: INotifyPropertyChanged { public SampleViewModel() { this.Text = "Hello, World!"; } private string _text; public string Text { get { return _text; } set { _text = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Text")); } } } public event PropertyChangedEventHandler PropertyChanged; } }
- 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> <TextBlock Text="{Binding Text}"/> </Grid> </Window>
TextをBindingさせてHello, world!を表示しただけ。
こんな造りしてたなというぐらいには忘れている。
少しずつ触って思い出していこう。