我使用MVVM和Caliburn.Micro,我遇到了问题。 所以我在视图中有2个组合框。首先是代表国家名单和第二个城市名单。我希望每当第一个列表中的国家/地区更改时,都会更新城市列表,并显示相应的城市列表。我的问题是城市名单没有更新。 这是我的代码:
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);
}
}
}
现在城市列表仍保留默认成员(DEFAULT,DEFAULT)。该视图仅包含2个具有相应名称的组合框:
<Grid>
<ComboBox x:Name="Countries" />
<ComboBox x:Name="Cities" />
</Grid>
一些建议? 抱歉我的英语不好。
答案 0 :(得分:0)
将国家/地区SelectedItem
的{{1}}属性绑定到视图模型的源属性:
ComboBox
...并在此设置器中为<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" };
}
}
}
}
:https://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/