我以编程方式创建一个WPF TabItem并将其添加到我的TabControl。
var tabItem = new TabItem { Header = "foo" };
现在我想做一些像
这样的事情 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.
这有可能吗?我知道在XAML中它不会有问题。但现有的架构迫使我尝试这种方式。
答案 0 :(得分:1)
我会做这样的事情:
StackPanel panel = new StackPanel();
panel.Children.Add(txt1);
panel.Children.Add(txt2);
var tabItem = new TabItem { Header = panel };
答案 1 :(得分:0)
OP要求以编程方式创建WPF TabItems
,并通过添加TabControl
添加到UserControls
,但如果您有List
或{对象{1}},您可以将它们绑定到Collection
,然后使用TabControl.ItemsSource
指定DataTemplates
和ItemTemplate
。
TabControl XAML:
ContentTemplate
用于TabControl的MyItem 类
<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 对象列表
public class MyItem {
public string HeaderA { get; set; }
public string HeaderB { get; set; }
public string MyContent { get; set; }
}
这样,您可以将 MyContent 更改为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."}
};
}
}
}
类,然后使用object
和DataTemplates
属性来指定ContentTemplate中显示的内容你的内容有不同的对象。