[英]Can't bind ObservableCollection to Combobox in wpf
我有以下xaml:
<UserControl.Resources>
<sivm:Locator x:Key="viewModelLocator" ModelType="{x:Type ViewModels:RateVSConcentrationViewModel}"/>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Path="ViewModel" Source="{StaticResource viewModelLocator}"/>
</UserControl.DataContext>
...
<ComboBox Grid.Column="0" Grid.Row="1" Height="20" VerticalAlignment="Top" ItemsSource="{Binding Chambers}" > <!--SelectedItem="{Binding SelectedChamber}">-->
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ChamberName}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Chambers
是對象的ObservableCollection
,其中包含一個名為ChamberName
的屬性,我希望在組合框中顯示該屬性。
在ViewModel中,我有以下代碼:
foreach (var chamber in chambers)
{
Chambers.Add(chamber);
}
OnPropertyChanged(() => Chambers);
但是,當執行此代碼時,組合框不會更新。 我已經使用這種方式進行了很多數據綁定,但是我無法使其正常工作。
有人可以在這里看到我做錯了嗎?
您可能需要在文本塊上設置相對源,嘗試將文本塊的Text屬性上的綁定修改為以下內容:
{Binding DataContext.ChamberName, RelativeSource={RelativeSource AncestorType=ComboBox}}
正如上面所說的,始終檢查綁定錯誤,它們將使您走上正確的道路。
您應該按如下所示調整屬性綁定:
<ComboBox ItemsSource="{Binding Path=ViewModel.Chambers, Source={StaticResource viewModelLocator}}" >
我做到了這一點:
<ComboBox DisplayMemberPath="ChamberName" Grid.Column="0" Grid.Row="1" Height="20" VerticalAlignment="Top" ItemsSource="{Binding Chambers}"> <!--SelectedItem="{Binding SelectedChamber}">-->
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.