你如何处理MVVM中的ComboBox SelectionChanged?选择已更改的事件未触发。

时间:2015-10-30 04:38:20

标签: wpf events mvvm combobox selectionchanged

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>
  

我想在第一个组合框中选择值,第二个组合框应该根据第一个组合框选择填充。

1 个答案:

答案 0 :(得分:0)

由于您使用的是MVVM,最简单的解决方案是将选定的comboboxItem逻辑放在其属性设置器中。 ViewModel应该实现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" />

属性可能如下所示:

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");
    }
}

或者您可以通过Command实现此功能,如讨论here