2017-07-07 80 views
-1

的我有两个组合框级联组合框没有更新的ItemSource依赖组合框

<ComboBox x:Name="cmbInstanceList" Margin="15,0,5,0" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding InstanceList}" SelectionChanged="cmbInstanceList_SelectionChanged" 

           Height="25" 
           Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}" />  
<ComboBox x:Name="cmbDatabaseList" Margin="15,0,5,0" Grid.Row="2" Grid.Column="1" ItemsSource="{Binding DatabaseList}" 

           Height="25" Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}" /> 

在此基础上cmbInstanceList,我填cmbDatabaseList通过的ItemSource属性。 InstanceListDatabaseList是List类型的模型属性。

在代码后端,我使用了selectedchanged事件来填充第二个组合框。

private void cmbInstanceList_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     { 
      if (cmbInstanceList.SelectedValue != null) 
      { 
       this.data.InstanceName = cmbInstanceList.SelectedValue.ToString(); 
       this.data.DatabaseList.Clear(); // this is not working 
       FillData(this.data.InstanceName); 
      } 
     } 

其中this.data表示包含所有属性的模型类。

FillData方法包含对服务的调用,如果数据不可用,返回数据值将只是一个空列表。

response = service.RequestDatabasesByInstance(request); 
       if (response != null) 
       { 
        if (response.DatabaseList != null && response.DatabaseList.Any()) 
         this.data.DatabaseList = response.DatabaseList.ToList<string>(); 
        else 
        { 
         this.data.DatabaseList.Clear(); 
         throw new Exception("No data available"); 
        } 
       } 

问题:当我选择从cmbInstance的价值和服务返回与价值观,所有的好,做工精细列表的响应。 当我选择值时,服务无法检索数据并返回空列表时出现问题。即使我设置了模型属性来清除项目,在UI上,我仍然可以看到组合框包含值和项目没有被清除。

+0

是'DatabaseList''ObservableCollection'? –

+0

@LeiYang其列表。它将与ObservableCollection一起工作吗? –

+0

在wpf中你最好使用UI绑定ObservableCollection –

回答

-1

我忘记了MVVM的基本概念。 我相信这个答案可能会帮助像我这样的人尝试在空间中寻找草地。

分辨率的问题是: 我已经改变

this.data.DatabaseList.Clear(); //这是不工作

this.data.DatabaseList = NULL;

它开始工作。从技术上讲,当我们改变属性的值时,触发PropertyChanged事件(在INotifyPropertyChanged接口中声明)通知绑定,然后更新视图。在我的情况下,我只是清除属性持有的集合对象,该属性并未触发PropertyChanged事件。

希望这可以帮助别人。

0

我已经忘记了MVVM

你似乎并不知道MVVM模式是怎么一回事......

处理在视图中SelectionChanged事件实施的基本概念级联ComboBoxes是而不是 MVVM。

取而代之,当设置与第一个ComboBoxSelectedItem属性绑定的源属性时,应该填充第二个ComboBox的源集合。在以下博客文章中有一个完整的示例和更多信息:https://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/

应该有如果您遵循MVVM模式,则在代码隐藏中与代码隐藏有关的代码隐藏ComboBoxes。您在此处介绍的解决方案不符合MVVM设计模式。