使用MVVM处理SelectedItem事件的最简单方法是什么?

时间:2009-06-18 09:34:52

标签: wpf mvvm selecteditem

在下面的代码中,当用户在组合框中选择客户时,客户的名称会在文本框中显示。我在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);
}

2 个答案:

答案 0 :(得分:12)

您应该能够将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>

答案 1 :(得分:10)

在www.codeproject.com上查看this应用程序。在这里,我使用CollectionView来检测当前选择的项目

<强>更新

使用CollectionView检测当前所选项目

ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(Customers); 
view.CurrentChanged += delegate 
{ 
    SelectedCustomer= (Customer)view.CurrentItem; 
};

请记住还要设置IsSynchronizedWithCurrentItem =“True”