2017-05-29 49 views
1

我使用MVVM與Caliburn.Micro,我有一個問題。 所以我有2個組合框視圖。首先是代表一個國家和第二個citites列表。我希望每當第一個列表中的國家發生變化時都要更新城市列表,並列出相應的城市列表。我的問題是城市列表不更新。 這裏是我的代碼:MVVM Caliburn.micro組合框國家城市不能正常工作

public class MyViewModel : PropertyChangedBase 
{ 
    Company company = new Company(); 
    List<string> countries = new List<string> {"USA","Germany" }; 
    public string Name 
    { 
     get { return company.name; } 
     set { company.name = value; 
     } 
    } 
    public List<string> Countries 
    { 
     get { return countries; } 
     set { 
      company.country = ToString(); 
      NotifyOfPropertyChange(() => Countries); 
      NotifyOfPropertyChange(() => Cities); 
     } 
    } 
    public List<string> Cities 
    { 
     get { 
      switch (company.country) 
      { 
       case "USA": return new List<string> { "New York", "Los Angeles" }; 
       case "Germany": return new List<string> { "Hamburg", "Berlin" }; 
       default: return new List<string> { "DEFAULT", "DEFAULT" }; 

      } 
      } 
     set { company.city = value.ToString(); 
      NotifyOfPropertyChange(() => Cities); 
     } 
    } 

} 

現在的城市名單仍與默認成員(默認值,默認值)。該視圖只包含2個相應名稱的組合框:

<Grid> 
     <ComboBox x:Name="Countries" /> 
     <ComboBox x:Name="Cities" /> 
</Grid> 

有些建議嗎? 對不起,我的英語不好。

回答

0

綁定全國ComboBox的向視圖模型的來源屬性SelectedItem屬性:

<ComboBox x:Name="Countries" ItemsSource="{Binding Countries}" SelectedItem="{Binding SelectedCountry}" /> 
<ComboBox x:Name="Cities" ItemsSource="{Binding Cities}" /> 

...,提高PropertyChanged事件爲Cities財產這一塊的二傳手:

public class MyViewModel : PropertyChangedBase 
{ 
    Company company = new Company(); 
    List<string> countries = new List<string> { "USA", "Germany" }; 
    public string SelectedCountry 
    { 
     get { return company.country; } 
     set 
     { 
      company.country = value; 
      NotifyOfPropertyChange(() => SelectedCountry); 
      NotifyOfPropertyChange(() => Cities); 
     } 
    } 
    public List<string> Countries 
    { 
     get { return countries; } 
     set 
     { 
      countries = value; 
      NotifyOfPropertyChange(() => Countries); 
      NotifyOfPropertyChange(() => Cities); 
     } 
    } 
    public List<string> Cities 
    { 
     get 
     { 
      switch (company.country) 
      { 
       case "USA": return new List<string> { "New York", "Los Angeles" }; 
       case "Germany": return new List<string> { "Hamburg", "Berlin" }; 
       default: return new List<string> { "DEFAULT", "DEFAULT" }; 

      } 
     } 
    } 
} 

有關如何實現這種級聯的完整示例和更多信息,請參閱以下博文:ComboBoxeshttps://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/