WPF数据绑定更新comboxbox2根据与MVVM的combobox1中的选择更改
问题描述:
我有一个组合框,我绑定到了我的viewmodel中存在的列表。现在,当用户在该组合框中进行选择时,我想要第二个组合框来更新其内容。WPF数据绑定更新comboxbox2根据与MVVM的combobox1中的选择更改
因此,例如,combobox1是States并且combobox2应该只包含该状态的Zipcode。
但在我的情况下,我没有为combobox2手动预定义列表,我需要从数据库获取。另外,如果需要,我可以事先为combobox2(对于每个combobox1值)获取所有潜在值,但是如果可以的话,我想避免这种情况。
如何在WPF中实现并使用MVVM?我对整个wpf \ databinding \ mvvm世界相当陌生。
答
像下面这样。请注意,为了举例,代码大大简化了。实际上,当属性被修改时,您的ViewModel将实现INotifyPropertyChanged并引发PropertyChanged事件。
关键虽然是SelectedState的setter。您的ComboBox会将其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
}
}
答
另一种解决方案。近似模型:
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 {...}
}
}
和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.清除集合添加新的拉链前 2.我肯定会尝试实现一个异步模式,你不希望屏幕冻结,直到电话回来。 3.如果实现异步方法,您可能需要禁用邮编组合,直到电话回来。 – Agies 2010-05-21 01:41:53