gpt4 book ai didi

c# - MVVM Caliburn.micro 组合框 Country-City 无法正常工作

转载 作者:行者123 更新时间:2023-12-03 10:43:10 24 4
gpt4 key购买 nike

我正在将 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)。该 View 仅包含 2 个具有相应名称的组合框:
<Grid>
<ComboBox x:Name="Countries" />
<ComboBox x:Name="Cities" />
</Grid>

一些建议?
对不起,我的英语不好。

最佳答案

绑定(bind)SelectedItem国家属性(property)ComboBox到 View 模型的源属性:

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

...并提高 PropertyChanged Cities 的事件这个 setter 中的属性:
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" };

}
}
}
}

有关如何实现这种级联的完整示例和更多信息,请参阅以下博客文章 ComboBoxes : https://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/

关于c# - MVVM Caliburn.micro 组合框 Country-City 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44240393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com