以编程方式添加和编辑控件

时间:2013-07-25 19:44:18

标签: c# wpf

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

2 个答案:

答案 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指定DataTemplatesItemTemplate

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."} }; } } } 类,然后使用objectDataTemplates属性来指定ContentTemplate中显示的内容你的内容有不同的对象。