50 votes

Comment gérer l'événement SelectionChanged de ComboBox avec MVVM dans wpf ?

Comment augmenter / gérer l' SelectionChanged ComboBox de WPF à l'aide du modèle MVVM ? Expliquez en détail s'il vous plaît, je suis nouveau sur WPF.

Ce que je veux, c'est effectuer certaines opérations lorsque la sélection d'éléments ComboBox changé. Comment puis-je y parvenir, d'une manière MVVM ?

71voto

snurre Points 2837

Solution MVVM :

Liez les propriétés ItemsSource et SelectedItem ComboBox aux propriétés de votre ViewModel :

 <ComboBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem}"/>

Dans MainViewModel.cs :

 public ObservableCollection<string> MyItems { get; set; }

private string _mySelectedItem;
public string MySelectedItem
{
  get { return _mySelectedItem; }
  set
  {
    // Some logic here
    _mySelectedItem = value;
  }
}

Solution code-behind :

Si vous ne souhaitez pas utiliser MVVM, vous pouvez ajouter ceci :

  <ComboBox SelectionChanged="ComboBox_SelectionChanged" />

Et ajoutez ceci dans MainWindow.xaml.cs :

 private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // Some logic here
}

44voto

Blackey Points 568

Je suis un grand fan de cette méthode.

 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<ComboBox Grid.Column="2"  DisplayMemberPath="Data.name" ItemsSource="{Binding Model.Regions}" SelectedItem="{Binding Model.SelectedRegion}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding RegionChangedCmd}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

6voto

Steven Licht Points 508

Votre ViewModel doit implémenter INotifyPropertyChanged.

 public class MyViewModel : INotifyPropertyChanged
{
    private string _mySelectedItem;
    public string MySelectedItem
    {
        get
        {
            return _mySelectedItem;
        }
        set
        {
            if (_mySelectedItem != value)
            {
                _mySelectedItem = value;
                // Perform any pre-notification process here.
                if (null != PropertyChanged)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("MySelectedItem"));
                }
            }
        }
    } 
}

Le XAML publié précédemment est correct :

 <ComboBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem}"/> 

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X