在为 ItemControl 编写 ItemTemplate 时候,需要使用到 UserControl 的 DataContext,即与绑定集合同等地位的属性,例如下述代码:
注意到在 ListBox 的绑定中,由于 ItemTemplate 默认绑定到了集合的单个对象,因此无法采用直接的方式绑定到 UserControl 的 DataContext 中的属性,即对应的 ViewModel.OtherCollections 。
因此,使用 FindAncestor 的绑定方式,通过获取 UserControl 的 DataContext ,继而间接绑定到 ViewModel 中的集合,ComboBox 的绑定代码如下:
其中 ViewModel.cs 相关代码如下:
Class ViewModel : ViewModelBase
{
// Other Definitions
//...
private ObservableCollection _collections;
public ObservableCollection Collections
{
get => _collections;
Set => Set(ref _collections, value);
}
public List OtherCollections => new List();
}



