您可以使用CompositeCollection 将多个集合绑定到同一个源。
Here is an example.
缺点是我认为在这种情况下分组是不可能的(至少不容易)。
另一种选择是只有一个列表,对象实现相同的接口,具有一些属性来区分项目的类型,例如:
public interface IHost : INotifyPropertyChanged
{
string HostType { get; }
string Hostname { get; set; }
string DisplayText { get; set; }
}
public class HistoryItem : IHost
{
public event PropertyChangedEventHandler PropertyChanged;
public string HostType => "History";
public string Hostname { get; set; }
public string DisplayText => Hostname;
}
public class FavoriteItem : IHost
{
public event PropertyChangedEventHandler PropertyChanged;
public string HostType => "Favorites";
public string Hostname { get; set; }
public string Description { get; set; }
public string DisplayText => Description == null ? Hostname : $"{Description} | {Hostname}";
//other properties....
}
因为我发现直接使用 ObservableCollection 很烦人,所以我倾向于使用包装器(代码在底部)。它处理一些常见问题,例如可能的内存泄漏和在添加多个项目时引发不必要的CollectionChanged 事件。它还提供对来自代码隐藏的分组、排序、过滤、当前项目和CurrentChanged 和CurrentChanging 事件的轻松访问。
在 ViewModel 中:
public ViewableCollection<IHost> MyItems { get; set; }
初始化集合:
this.MyItems = new ViewableCollection<IHost>();
// decide how your items will be sorted (important: first sort groups, then items in groups)
this.MyItems.View.SortDescriptions.Add(new SortDescription("HostType", ListSortDirection.Ascending)); // sorting of groups
this.MyItems.View.SortDescriptions.Add(new SortDescription("Hostname", ListSortDirection.Ascending)); // sorting of items
PropertyGroupDescription groupDescription = new PropertyGroupDescription("HostType");
this.MyItems.View.GroupDescriptions.Add(groupDescription);
this.MyItems.View.CurrentChanged += MyItems_CurrentChanged;
this.MyItems.AddRange(new IHost[] {
new HistoryItem { Hostname = "ccc" },
new HistoryItem { Hostname = "aaa" },
new HistoryItem { Hostname = "xxx" },
new FavoriteItem { Hostname = "vvv" },
new FavoriteItem { Hostname = "bbb" },
new FavoriteItem { Hostname = "ttt" } });
当项目被选中时,此代码将执行:
private void MyItems_CurrentChanged(object sender, EventArgs e)
{
Console.WriteLine("Selected item: " + this.MyItems.CurrentItem?.Hostname);
}
这是ComboBox 的xaml 与分组(使用ViewableCollection,您需要将ItemsSource 绑定到MyItems.View 而不是直接绑定到MyItems):
<ComboBox ItemsSource="{Binding MyItems.View, Mode=OneWay}"
IsSynchronizedWithCurrentItem="True"
DisplayMemberPath="DisplayText">
<ComboBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Items.CurrentItem.HostType, StringFormat=[{0}]}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ComboBox.GroupStyle>
</ComboBox>
结果:
[DoNotNotify]
public class ViewableCollection<T> : ObservableCollection<T>
{
private ListCollectionView _View;
public ViewableCollection(IEnumerable<T> items)
: base(items) { }
public ViewableCollection()
: base() { }
[XmlIgnore]
public ListCollectionView View
{
get
{
if (_View == null)
{
_View = new ListCollectionView(this);
_View.CurrentChanged += new EventHandler(InnerView_CurrentChanged);
}
return _View;
}
}
[XmlIgnore]
public T CurrentItem
{
get
{
return (T)this.View.CurrentItem;
}
set
{
this.View.MoveCurrentTo(value);
}
}
private void InnerView_CurrentChanged(object sender, EventArgs e)
{
this.OnPropertyChanged(new PropertyChangedEventArgs("CurrentItem"));
}
public void AddRange(IEnumerable<T> range)
{
if (range == null)
throw new ArgumentNullException("range");
foreach (T item in range)
{
this.Items.Add(item);
}
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public void ReplaceItems(IEnumerable<T> range)
{
if (range == null)
throw new ArgumentNullException("range");
this.Items.Clear();
foreach (T item in range)
{
this.Items.Add(item);
}
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public void RemoveItems(IEnumerable<T> range)
{
if (range == null)
throw new ArgumentNullException("range");
foreach (T item in range)
{
this.Items.Remove(item);
}
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public void ClearAll()
{
IList old = this.Items.ToList();
base.Items.Clear();
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public void CallCollectionChaged()
{
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
// necessary for xml easy serialization using [XmlArray] attribute
public static implicit operator List<T>(ViewableCollection<T> o)
{
return o == null ? default(List<T>) : o.ToList();
}
// necessary for xml easy serialization using [XmlArray] attribute
public static implicit operator ViewableCollection<T>(List<T> o)
{
return o == default(List<T>) || o == null ? new ViewableCollection<T>() : new ViewableCollection<T>(o);
}
}
上面的代码是一个工作示例。我正在使用 nuget 包 PropertyChanged2.Fody 来注入 PropertyChanged 通知。