以下のコードでは、ユーザーがコンボボックスでCustomer を選択すると、顧客の名前がテキストボックスに表示されます。Combox ボックスに ViewModel の ObservableCollection プロパティを入力しましたが、ViewModel で SelectedItem イベントを処理するにはどうすればよいですか?
以下に示すようにコード ビハインドを使用してこれを実装するのは簡単ですが、MVVM パターンでこれを行うにはどうすればよいですか?
現在、使用できる基本的な MVVM テンプレートにDelegateCommandとAttachedBehaviorsがありますが、「コンボボックスが新しい項目を選択した」ときにそれらを起動する方法がわかりません。
意見:
<Window.Resources>
<DataTemplate x:Key="CustomerTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<DockPanel LastChildFill="False" Margin="10">
<ComboBox
x:Name="CustomerList"
ItemTemplate="{StaticResource CustomerTemplate}"
HorizontalAlignment="Left"
DockPanel.Dock="Top"
Width="200"
SelectionChanged="CustomerSelected"
ItemsSource="{Binding Customers}"/>
<TextBlock x:Name="CurrentlySelectedCustomer"/>
</DockPanel>
コードビハインド:
private void CustomerSelected(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
Customer customer = (Customer)CustomerList.SelectedItem;
CurrentlySelectedCustomer.Text = String.Format("{0} {1}", customer.FirstName, customer.LastName);
}