What is the easiest way to handle SelectedItem event with MVVM?

后端 未结 2 845
萌比男神i
萌比男神i 2021-02-02 02:10

In the code below, when user selects Customer in the combobox, the customer\'s name is displayed in a textbox. I fill the Combox box with an O

相关标签:
2条回答
  • 2021-02-02 02:25

    You should be able to bind a property in you ViewModel to the SelectedItem property of the combobox. If you set this up as two way binding you will be notified when the SelectedItem is changed because it will trigger the set method on the property.

    ViewModel:

    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>
    
    0 讨论(0)
  • 2021-02-02 02:32

    Have a look at this application on www.codeproject.com. Here I use the CollectionView to detect the currently selected item

    Update

    Using CollectionView to detect current selected item

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

    Just remember to also set IsSynchronizedWithCurrentItem="True"

    0 讨论(0)
提交回复
热议问题