![](/img/trans.png)
[英]How to bind one ObservableCollection as ItemsSource to different comboBoxes (models) if using wpf ItemsControl with MVVM pattern?
[英]WPF (mvvm) databinding itemssource and selecteditem to different models
我遇到了WPF數據綁定問題,但是我沒有過去。 我有如下的MVVM設置:
public class ModelA
{
public int Id
{
//Property uses INotifyPropertyChanged
}
}
public class ModelB
{
public ModelA The_A
{
//Property uses INotifyPropertyChanged
}
}
public class ViewModel
{
public IEnumerable<ModelA> ModelAList
{
//Property uses INotifyPropertyChanged
}
public IEnumerable<ModelB> ModelBList
{
//Property uses INotifyPropertyChanged
}
}
我的XAML的DataContext是ViewModel(驚奇),我在其中有了這個ListBox:
<ListBox ItemsSource="{Binding ModelBList}">
<ListBox.ItemTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.ModelAList"
SelectedItem="{Binding The_A}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
當我打開窗口時,ComboBox尚未選擇任何項,但是如果我從復選框中選擇某項,則The_A將設置為我選擇的任何項。
我的猜測是我的ModelAList中的ModelA與ModelB中的ModelA不同。 有什么辦法可以使此數據綁定工作? 也許我缺少明顯的東西,或者我沒有正確地解決問題。
非常感謝!
您的數據綁定似乎是錯誤的。 這就是為什么它不起作用。 由於您的視圖意外地綁定到ViewModel
類,因此該ViewModel
類應該保留來自相應視圖的所有綁定。
好吧,您已將您的itemssource正確綁定到ModelAList IEnumerable。
但是所選項目綁定到其他某個類的屬性。 因此,它將不起作用。 另外,您還需要將所選項目設置為用於您的itemsource的數據類型。
因此,在ViewModel
類中創建一個屬性,如下所示:
private ModelA _selectedComboBoxItem;
public ModelA SelectedComboBoxItem
{
get { return _selectedComboBoxItem; }
set
{
_selectedComboBoxItem = value;
Propertychanged(this, "SelectedComboBoxItem");
}
}
然后將其綁定到SelectedItem,如下所示:
SelectedItem="{Binding SelectedComboBoxItem}"
這顯然應該起作用。
編輯:按要求添加更多詳細信息。
假設您有十二個橙子。 如果您讓一個人從他們那里隨機挑選,您會得到什么? 橘子本身對嗎? 這也是其背后的想法。 如果選擇組合框項目,則其類型將與其來源相同。
如果同一列表項中有許多組合框,則可以更改ItemsSource數據類型以容納這么多列表或屬性。
例如:說我有一個帶有2個組合框和2個文本框的列表。 因此,我的itemssource將是ObservableCollection,並且此observable集合將包含2個可枚舉以及2個用於容納4個控件值的字符串。 如果需要,您還可以創建2個其他屬性來綁定每個組合框的選定項目。
經過一番討價還價,我找到了解決問題的辦法。 IDisposable的答案在此處指出,組合框無法一次綁定到兩個單獨的對象。 因此,當實例化ViewModel時(以及在加載ModelA的列表之后),可以將該列表復制到每個ModelB中進行綁定。 解決方案如下。
public class ModelA
{
public int Id
{
//Property uses INotifyPropertyChanged
}
}
public class ModelB
{
public ModelA The_A
{
//Property uses INotifyPropertyChanged
}
public IEnumerable<ModelA> The_A_List
{
//Property uses INotifyPropertyChanged
}
}
public class ViewModel
{
public ViewModel()
{
//Load lists
foreach (var b in ModelBList)
{
b.The_A_List = ModelAList;
}
}
public IEnumerable<ModelA> ModelAList
{
//Property uses INotifyPropertyChanged
}
public IEnumerable<ModelB> ModelBList
{
//Property uses INotifyPropertyChanged
}
}
然后在xaml中提供以下綁定:
<ListBox ItemsSource="{Binding ModelBList}">
<ListBox.ItemTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding The_A_List}"
SelectedItem="{Binding The_A}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
一切都很好。 再次感謝IDisposable提供的幫助,這使我踏上了開悟的道路。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.