Search This Blog

Wednesday, July 13, 2011

WPF clone tabItem; WPF create TabItems dynamically; WPF cannot edit TabItems controls; WPF cannot access TabItems controls;

It is impossible to clone TabItems from an existing one without using XamlReader and XamlWriter. You can, however, define a template for creating new TabItems. The template has to be created in your xaml file in Window resources.

<Window.Resources>
  <DataTemplate x:Key="tabItemContent">
            <Canvas Margin="0,0,0,0" Name="tabPracownikCanvas" Visibility="Visible">
                <ListBox Canvas.Left="0" Canvas.Top="-0.004" Height="229.977" Name="listBox1" Width="152.207">
                    <ListBoxItem>Dane osobowe</ListBoxItem>
                    </ListBox>
                <RichTextBox  Canvas.Left="0" Canvas.Top="261.085" Height="246.642" Name="richTextBoxBasicInfo" Width="152.207" IsReadOnly="True"/>
                <Label Canvas.Left="0" Canvas.Top="233.31" Height="27.775" Name="label1" Width="152.207" Content="SomeTextHere">
                </Label>
                <Canvas Canvas.Left="155.54" Canvas.Top="-0.018" Height="507.745" Name="canvasWithDetailedInfo" Width="430.731" >
                </Canvas>
            </Canvas>
        </DataTemplate>
</Window.Resources>

To add new tabItem just do the following:

TabItem item = new TabItem();
item.Header = "New item";
item.ContentTemplate = TryFindResource("tabItemContent") as DataTemplate;
tabControl2.Items.Add(item);

YOU CANNOT change the contents which were created dynamically just through children editing. You need to bind some properties.

e.g. we will bind label contents:

create a class:

        class Person
        {
            public string Name { get; set; }

            public string Surname { get; set; }
        }

change the label content to binding:

<Label Canvas.Left="0" Canvas.Top="233.31" Height="27.775" Name="label1" Width="152.207" Content="{Binding Name}">

change the Item’s content:

item.Content = new Person() { Name = "dupa", Surname = "xxxx" }

It will automatically change the label’s content when you change item.Content.Name property.

 

5 comments:

  1. You can also do it in this way:
    < Label Canvas.Left="0" Canvas.Top="233.31" Height="27.775" Name="label1" Width="152.207">



    < /Label>

    ReplyDelete
  2. WPF Charts developing can be tricky, especially if you're an inexperienced developer. Thankfully there are these great WPF charting posts available on the web, such as this one, that help us those inexperienced developers gather knowledge about iOS Charts, Android charts and other types of WPF charts. Thank you for your post.

    ReplyDelete

If you like this post, please leave a comment :)