在下面的代码中,当用户选择客户时在组合框中,显示客户姓名在文本框中。我在 ViewModel 上使用 ObservableCollection 属性填充 Combobox,但如何处理 ViewModel 中的 SelectedItem 事件?
使用隐藏代码很容易实现这一点,如下所示,但是我如何使用 MVVM 模式做到这一点?
我目前有委托命令 and 依恋行为在我可以使用的基本 MVVM 模板中,但我不知道如何在“组合框选择一个新项目”时触发它们。
View:
<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);
}
您应该能够将 ViewModel 中的属性绑定到组合框的 SelectedItem 属性。如果将其设置为双向绑定,当 SelectedItem 更改时您将收到通知,因为它将触发属性上的 set 方法。
视图模型:
public ObservableCollection Customers
{
get { return _customers; }
set
{
if (_customers != value)
{
_customers = value;
OnPropertyChanged("Customers");
}
}
}
public Customer SelectedCustomer
{
get { return _selectedCustomer; }
set
{
if (_selectedCustomer != value)
{
_selectedCustomer= value;
LastName= value.LastName;
OnPropertyChanged("SelectedCustomer");
}
}
}
public Customer LastName
{
get { return _lastName; }
set
{
if (_lastName!= value)
{
_lastName= value;
OnPropertyChanged("LastName");
}
}
}
Xaml:
<DockPanel LastChildFill="False" Margin="10">
<ComboBox
x:Name="CustomerList"
ItemTemplate="{StaticResource CustomerTemplate}"
HorizontalAlignment="Left"
DockPanel.Dock="Top"
Width="200"
SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
ItemsSource="{Binding Customers}"/>
<TextBlock x:Name="CurrentlySelectedCustomer"
Text="{Binding LastName}"/>
</DockPanel>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)