2010-05-19 152 views
3

我有一個組合框,我綁定到了我的viewmodel中存在的列表。現在,當用戶在該組合框中進行選擇時,我想要第二個組合框來更新其內容。WPF數據綁定更新comboxbox2根據與MVVM的combobox1中的選擇更改

因此,例如,combobox1是States並且combobox2應該只包含該狀態的Zipcode。

但在我的情況下,我沒有爲combobox2手動預定義列表,我需要從數據庫獲取。另外,如果需要,我可以事先爲combobox2(對於每個combobox1值)獲取所有潛在值,但是如果可以的話,我想避免這種情況。

如何在WPF中實現並使用MVVM?我對整個wpf \ databinding \ mvvm世界相當陌生。

回答

2

像下面這樣。請注意,爲了舉例,代碼大大簡化了。實際上,當屬性被修改時,您的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 
    } 

} 
+0

只是一對夫婦可能明顯的提示添加... 1.清除集合添加新的拉鍊前 2.我肯定會嘗試實現一個異步模式,你不希望屏幕凍結,直到電話回來。 3.如果實現異步方法,您可能需要禁用郵編組合,直到電話回來。 – Agies 2010-05-21 01:41:53

0

另一種解決方案。近似模型:

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>