我已经在SO上查看了几个问题/答案,由于某种原因,我没有得到任何工作来将一个集合绑定到TabControl
。我试图这样做,所以我不 在代码隐藏中分配DataContext
。
以下是视图模型:
public class DocumentsCollectionViewModel : IEnumerable<DocumentViewModel> {
private readonly ObservableCollection<DocumentViewModel> mDocsCollection = new ObservableCollection<DocumentViewModel>();
public ObservableCollection<DocumentViewModel> Documents {
get { return mDocsCollection; }
}
// initially excluded from question as I thought it was understood :)
public IEnumerator<DocumentViewModel> GetEnumerator() {
return mDocsCollection.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return mDocsCollection.GetEnumerator();
}
}
...为了完整起见,DocumentViewModel
:
public class DocumentViewModel {
private readonly Document mDocument;
public string Name {
get { return mDocument.Name; }
}
}
在XAML中,我对使用标签控件在Documents
中使用DocumentsCollectionViewModel
属性的位置感到有些困惑:
<TabControl Name="DocumentsTab"
ItemsSource="{Binding localmodels:DocumentsCollectionViewModel}">
<TabControl.ItemTemplate>
<DataTemplate DataType="{x:Type localmodels:DocumentViewModel}">
<Label Style="{StaticResource DefaultFont}"
Content="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type localmodels:DocumentViewModel}">
<Label Style="{StaticResource DefaultFont}"
Content="{Binding Name}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
答案 0 :(得分:2)
您是否已将DataContext
/ UserControl的Window
设置为TabControl
的实例?
尝试在包含TabControl
的Window的构造函数中执行此操作DocumentsCollectionViewModel
或者您可以在xaml中设置DataContext,如
public void MainWindow()
{
InitializeComponents();
this.DataContext = new DocumentsCollectionViewModel();
//Initialize the collection inside your VM
}
然后在你的xaml中直接绑定到<Window>
<Window.DataContext>
<localmodels:DocumentsCollectionViewModel/>
</Window.DataContext>
</Window>
属性
Documents