子组合框显示父组合框选择值项目以外的值

时间:2015-11-13 05:09:03

标签: c# wpf combobox

XAML

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

            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">

                    <i:InvokeCommandAction Command="{Binding serverCommand}" CommandParameter="{Binding ElementName=comboBoxServer,Path=SelectedItem}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ComboBox

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

查看模型

父组合框:_ServerNameList 子组合框是:_DBNameList

ViewModel构造函数

     public BackUpViewModel()
            {                       
                BackUpContext servObj = new BackUpContext();
                _ServerNameList = servObj.GetServers();     

                serverCommand = new RelayCommand(fetchServer);
            }

public RelayCommand serverCommand { get; set; }
public void fetchServer(object server)
            {
                 BackUpContext db= new BackUpContext();            
                 serverSelected = server.ToString();
                _DBNameList = db.GetDatabases(serverSelected);           
            }
  

当我在父组合框中选择第一项时,子组合框为空白。之后当我在父组合框中选择第二项时,该子项显示与父项中第一项相关的项。当我在Parent中选择第三项时,子项显示与父组合框中的第二项相关的项目。

     

我不知道为什么会这样。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您必须为第二个ComboBox设置值。

public BackUpViewModel()
{                       
    BackUpContext servObj = new BackUpContext();
   _ServerNameList = servObj.GetServers();     

   // Select the first.
   fetchServer(_ServerNameList.FirstOrDefault());
}