WPF数据绑定基于带有MVVM的combobox1中的选择更改更新comboxbox2
我有一个组合框,已绑定到viewmodel中存在的列表。现在,当用户在该组合框中进行选择时,我需要第二个组合框来更新其内容 例如,combobox1是States,combobox2应该只包含该状态的Zipcodes 但是在我的例子中,我手头没有combobox2的预定义列表,我需要从数据库中获取 此外,如果需要,我可以事先获得combobox2的所有潜在值(每个combobox1值),但如果可以的话,我希望避免这样做WPF数据绑定基于带有MVVM的combobox1中的选择更改更新comboxbox2,wpf,data-binding,mvvm,Wpf,Data Binding,Mvvm,我有一个组合框,已绑定到viewmodel中存在的列表。现在,当用户在该组合框中进行选择时,我需要第二个组合框来更新其内容 例如,combobox1是States,combobox2应该只包含该状态的Zipcodes 但是在我的例子中,我手头没有combobox2的预定义列表,我需要从数据库中获取 此外,如果需要,我可以事先获得combobox2的所有潜在值(每个combobox1值),但如果可以的话,我希望避免这样做 如何在WPF中实现并使用MVVM?我对整个wpf\databinding\m
如何在WPF中实现并使用MVVM?我对整个wpf\databinding\mvvm的世界还相当陌生。类似于以下内容。注意,为了举例,代码被大大简化了。实际上,ViewModel将实现INotifyPropertyChanged,并在修改属性时引发PropertyChanged事件 但关键是SelectedState的setter。组合框将其SelectedValue属性绑定到ViewModel的SelectedState属性。当属性更改时,ZipCodes集合将被重新加载,另一个组合框将绑定到该集合
class MyViewModel {
public ObservableCollection<string> States {
get;
private set;
}
public ObservableCollection<string> ZipCodes {
get;
private set;
}
public string SelectedState {
get { return _selectedState; }
set {
_selectedState = value;
LoadZipCodes(_selectedState);
}
}
public string SelectedZipCode {
get;
set;
}
void LoadZipCodes(string state) {
// repopulate the ZipCodes property
}
}
类MyViewModel{
公共可观测收集状态{
得到;
私人设置;
}
公共可观测收集ZipCodes{
得到;
私人设置;
}
公共字符串SelectedState{
获取{return\u selectedState;}
设置{
_selectedState=值;
加载ZipCodes(_selectedState);
}
}
公共字符串SelectedZipCode{
得到;
设置
}
void LoadZipCodes(字符串状态){
//重新填充ZipCodes属性
}
}
另一种解决方案。近似模型:
class StateViewModel
{
public string StateName
{
get {...}
set {...}
}
public ObservableCollection<ZipCodeViewModel> ZipCodes
{
get {...}
set {...}
}
}
class ZipCodeViewModel
{
public string ZipCodeName
{
get {...}
set {...}
}
}
class MainViewModel
{
public ObservableCollection<StateViewModel> States
{
get {...}
set {...}
}
}
class StateViewModel
{
公共字符串状态名
{
获取{…}
集合{…}
}
公共可观测收集ZipCodes
{
获取{…}
集合{…}
}
}
类ZipCodeViewModel
{
公共字符串ZipCodeName
{
获取{…}
集合{…}
}
}
类MainViewModel
{
公共可观测收集状态
{
获取{…}
集合{…}
}
}
和XAML:
<ComboBox ItemsSource="{Binding Path=States}" IsSynchronizedWithCurrentItem="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=StateName}"></Label>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ContentControl Content="{Binding Path=States}">
<ContentControl.ContentTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=ZipCodes}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=ZipCodeName}"></Label>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
只需添加几个明显的提示。。。1.在添加新Zips 2之前清除集合。我肯定会尝试实现一个异步模式,在调用返回之前,您不会希望屏幕冻结。3.如果实现异步方法,您可能希望禁用Zip组合,直到调用返回。