Aman Jain
Aman Jain

Reputation: 41

How do you handle a ComboBox SelectionChanged in MVVM? Selection changed events are not firing.

ComboBox1

  <ComboBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Center" Margin="2,2,0,0" Name="comboBoxServer" VerticalAlignment="Top" Width="156" ItemsSource="{Binding Path=ServerNameList, Mode=OneWay}" SelectedIndex="0" SelectedItem="{Binding SelectedIndex}" SelectionChanged="comboBoxServer_SelectionChanged" Text="{Binding selectedServer, Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged}" >
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="SelectionChanged">
                        <i:InvokeCommandAction Command="{Binding serverCommand}" CommandParameter="{Binding ElementName=comboBoxServer, Path=SelectedValue}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </ComboBox>

ComboBox2

            <ComboBox Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Center" Margin="2,2,0,0" Name="comboBoxDBName" VerticalAlignment="Top" Width="156" ItemsSource="{Binding Path=DBNameList, Mode=OneWay}" SelectedItem="{Binding serverSelected, Mode=TwoWay}" >

            </ComboBox>

I want that on selecting value in first combo box, Second combo box should populate according to first combo box selection.

Upvotes: 0

Views: 3730

Answers (1)

Fragment
Fragment

Reputation: 1585

Since you are using MVVM, the simplest solution will be to place the selected comboboxItem logic in its property setter. ViewModel should implement INotifyPropertyChanged:

<ComboBox
    Grid.Row="0" Grid.Column="0" 
    ItemsSource="{Binding Path=AvailableItems}"
    SelectedValue="{Binding Path=SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    Margin="3" />

<ComboBox
    Grid.Row="1" Grid.Column="0" 
    ItemsSource="{Binding Path=AvailableServers}"
    SelectedValue="{Binding Path=SelectedServer, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
    Margin="3" />

And properties can look like:

private Item selectedItem;
public Item SelectedItem
{
    get { return selectedItem; }
    set
    {
        selectedItem = value;

        ChangeSelectedServer();
        OnPropertyChanged("SelectedItem");
    }
}

private void ChangeSelectedServer()
{
    switch(selectedItem)
    {
        case ...
            // your setting logic here...
            // like: SelectedServer = AvailableServers.Where(s => s.Id == selectedItem.Id).Single();
            break;
    }
}

private Item selectedServer;
public Item SelectedServer
{
    get { return selectedServer; }
    set
    {
        selectedServer = value;
        OnPropertyChanged("SelectedServer");
    }
}

Or you can implement this through Command, like discussed here

Upvotes: 1

Related Questions