简体   繁体   中英

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:

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.

Bind the ItemsSource of the the TabControl to an ObservableCollection , then you just need to add items to that collection. Use the ItemTemplate (header) and ContentTemplate (tab item content) to create the tabs from the items in the collecton dynamically.

First of all, be careful with how you are using the word "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. What you should be doing is binding the ItemsSource of the TabControl to a collection in the viewmodel. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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