MVVM を使用した例を次に示します。
私の顧客モデルは非常に単純で、次のようになります。
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
次に、アプリケーションの MainWindow がバインドされる ViewModel が必要です。顧客を保持し、ボタンを使用して顧客間を移動するためのメソッドを備えています。CollectionView タイプは現在のアイテムの追跡をサポートしており、WinForms の BindingSource のようなものだと思います:
public class MyViewModel
{
public ICollectionView Customers { get; set; }
public void MoveSelectionLeft()
{
Customers.MoveCurrentToPrevious();
}
public void MoveSelectionRight()
{
Customers.MoveCurrentToNext();
}
public MyViewModel()
{
Customers = new CollectionViewSource
{
Source = new[]
{
new Customer {Name = "John", Age = 25},
new Customer {Name = "Jane", Age = 27},
new Customer {Name = "Dawn", Age = 31}
}
}.View;
}
}
次に、ビューがあります。ボタンへのアクションの接続を簡素化するために、Caliburn Micro を使用しています。ダウンロードして、Caliburn.Micro.dll への参照をプロジェクトに追加するだけです。
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org" Title="MainWindow" Height="400" Width="400">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.RowSpan="2" ItemsSource="{Binding Customers}" DisplayMemberPath="Name"/>
<DockPanel Grid.Column="1" LastChildFill="False">
<Button DockPanel.Dock="Left" Content="<"
cal:Message.Attach="[Event Click] = [MoveSelectionLeft]"/>
<Button DockPanel.Dock="Right" Content=">"
cal:Message.Attach="[Event Click] = [MoveSelectionRight]"/>
</DockPanel>
<StackPanel Grid.Row="1" Grid.Column="1">
<DockPanel>
<TextBlock MinWidth="50" Text="Name" Margin="0,0,5,0"/>
<TextBox Text="{Binding Customers/Name}"/>
</DockPanel>
<DockPanel>
<TextBlock MinWidth="50" Text="Age" Margin="0,0,5,0"/>
<TextBox Text="{Binding Customers/Age}"/>
</DockPanel>
</StackPanel>
</Grid>
MyViewModel の Customers プロパティにバインドされた ListBox、ボタンの Click イベントが MoveSelection メソッドに関連付けられているボタン、および Customer フィールドが Customers/ プロパティ (Customers.CurrentItem の略) にバインドされています。
これが WPF アプリの MainWindow であると仮定すると、次に行う必要があるのは、その DataContext を MyViewModel に設定することだけです。これは、コード ビハインドのコンストラクターに次を追加することで実行できます。
public MainWindow()
{
this.DataContext = new MyViewModel();
InitializeComponent();
}
アプリケーションをビルドして実行できるように、すべてをセットアップする必要があります。次のようになります。
