2

我以编程方式创建 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 中这不是问题。但是现有的架构迫使我尝试这种方式。

4

2 回答 2

1

我会做这样的事情:

StackPanel panel = new StackPanel();
panel.Children.Add(txt1);
panel.Children.Add(txt2);

var tabItem = new TabItem { Header = panel };
于 2013-07-25T19:49:24.307 回答
0

OP 要求以编程方式创建 WPFTabItemsTabControl通过添加 来添加到 中UserControls,但是如果您有对象ListCollection对象,则可以将它们绑定到TabControl.ItemsSourcethen 用于 DataTemplates指定ItemTemplateand 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>

用于 TabControl 的MyItem类

public class MyItem {
    public string HeaderA { get; set; }
    public string HeaderB { get; set; }
    public string MyContent { get; set; }
}

MyItem对象列表

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."}
            };
        }
    }
}

这样,您可以将MyContent更改为一个object类,然后使用DataTemplatesDataType属性来指定在 ContentTemplate 中显示的内容,如果您的内容有不同的对象。

于 2013-07-25T20:54:44.607 回答