Reputation: 3500
I create programmatically an WPF TabItem and added it to my TabControl.
var tabItem = new TabItem { Header = "foo" };
Now I want to do something like
var txt1 = new TextBlock { Text = "foo" };
var txt2 = new TextBlock { Text = "bar" };
var tabItem = new TabItem { Header = txt1 + txt2 }; // cannot apply operator + to TextBlock and TextBlock
// Other Idea:
// var tabItem = new TabItem { Header = new TextBlock { Text = "foo" }.Text + new TextBlock { Name = "txt2", Text = "bar" }};
// Maybe I could edit my TextBlock via it's name?
...
txt2.Text = "editedBar"; // have to update the header of tabItem.
Is this anyway possible? I know in XAML it wouldn't be a problem. But the existing architecture forces me to try this way.
Upvotes: 2
Views: 625
Reputation: 4002
The OP asked for a programmatical way to create WPF TabItems
and add to the TabControl
, through the adding of UserControls
, but if you have a List
or Collection
of your objects, you can bind them to the TabControl.ItemsSource
then use DataTemplates
to specify the ItemTemplate
and ContentTemplate
.
TabControl XAML:
<TabControl ItemsSource="{Binding MyItems}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{} {0}{1}">
<Binding Path="HeaderA"/>
<Binding Path="HeaderB"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<Binding Path="MyContent"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
MyItem class being used for TabControl
public class MyItem {
public string HeaderA { get; set; }
public string HeaderB { get; set; }
public string MyContent { get; set; }
}
List of MyItem objects
public List<MyItem> MyItems {
get {
return new List<MyItem>() {
new MyItem() {
HeaderA = "Foo0",
HeaderB = "Bar0",
MyContent = "This is content."
},
new MyItem() {
HeaderA = "Foo1",
HeaderB = "Bar1",
MyContent = "This is content."}
};
}
}
}
This way, you can change MyContent into an object
class, then use DataTemplates
with the DataType
attribute to specify what to show in ContentTemplate if they you have different objects for your content.
Upvotes: 0
Reputation: 9565
I would do something like this:
StackPanel panel = new StackPanel();
panel.Children.Add(txt1);
panel.Children.Add(txt2);
var tabItem = new TabItem { Header = panel };
Upvotes: 1