【发布时间】:2010-11-03 22:45:33
【问题描述】:
在下面的代码中,当用户在组合框中选择客户时,客户的姓名会显示在文本框中。我使用 ViewModel 上的 ObservableCollection 属性填充 Combox 框,但如何处理 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);
}
【问题讨论】:
标签: wpf mvvm selecteditem