如何正确数据绑定到TabControl?

时间:2014-06-20 02:24:32

标签: c# wpf data-binding tabcontrol

我已经在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>

1 个答案:

答案 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