简体   繁体   English

绑定控件名称问题

[英]Binding control name problem

I have in the mainwindow this code: 我在主窗口中有以下代码:

<TabControl x:Name="tc" Margin="0" SelectedIndex="0">
    <TabItem Header="Tab 1" Width="150"
             IsSelected="false">
        <!--<TextBox Width="200" Height="200"/>-->
    </TabItem>
</TabControl>

i have a mainwindowviewmodel and i want it to bind to the controltab name which is tc: 我有一个mainwindowviewmodel,我希望它绑定到tc的controltab名称:

private void AddTab_Execute(object parm)
{
    s = s + 1;
    TabItem Item = new TabItem();
    Item.Width = 150;
    Item.Header = "Tab " + s;
    tc.Items.Add(Item);
}

he doesn't recognize tc what do i have to do ? 他不认识我,我该怎么办?

This has nothing to do with binding , but it would be easier if you had one. 这与绑定无关,但是如果有绑定的话会更容易。 You should not need to reference controls like the TabControl in the view-model. 您无需在视图模型中引用诸如TabControl类的TabControl

Bind the ItemsSource of the the TabControl to an ObservableCollection , then you just need to add items to that collection. 将TabControl的ItemsSource绑定到ObservableCollection ,然后只需要向该集合添加项目即可。 Use the ItemTemplate (header) and ContentTemplate (tab item content) to create the tabs from the items in the collecton dynamically. 使用ItemTemplate (标题)和ContentTemplate (选项卡项目的内容)可以通过collecton中的项目动态创建选项卡。

First of all, be careful with how you are using the word "bind". 首先,请谨慎使用“ bind”一词。 That has a particular meaning which is not what you are doing in your example. 这具有特定的含义,这不是您在示例中所做的。 To see what binding actually means, check out this article . 要了解绑定的实际含义,请查看本文

You cannot access controls in your UI from your viewmodel. 您无法从视图模型访问UI中的控件。 What you should be doing is binding the ItemsSource of the TabControl to a collection in the viewmodel. 您应该做的是将TabControl的ItemsSource绑定到视图模型中的集合。 You can create DataTemplateSelectors and use them for the TabControl's ContentTemplateSelector and ItemTemplateSelector if you want to select different templates depending on the item which is bound to each TabItem. 如果要根据绑定到每个TabItem的项目选择不同的模板,则可以创建DataTemplateSelector并将其用于TabControl的ContentTemplateSelectorItemTemplateSelector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM