[英]Programmatically add and edit controls
I create programmatically an WPF TabItem and added it to my TabControl. 我以编程方式创建WPF TabItem,并将其添加到我的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. 我知道在XAML中不会有问题。 But the existing architecture forces me to try this way. 但是现有的架构迫使我尝试这种方式。
I would do something like this: 我会做这样的事情:
StackPanel panel = new StackPanel();
panel.Children.Add(txt1);
panel.Children.Add(txt2);
var tabItem = new TabItem { Header = panel };
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
. OP要求以编程方式创建WPF TabItems
并通过添加UserControls
将其添加到TabControl
,但是如果您具有对象的List
或Collection
,则可以将它们绑定到TabControl.ItemsSource
然后使用DataTemplates
指定ItemTemplate
和ContentTemplate
。
TabControl XAML: 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 用于TabControl的MyItem类
public class MyItem {
public string HeaderA { get; set; }
public string HeaderB { get; set; }
public string MyContent { get; set; }
}
List of MyItem objects 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."}
};
}
}
}
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. 这样,您可以将MyContent更改为object
类,然后使用具有DataType
属性的DataTemplates
来指定在内容模板中具有不同对象时在ContentTemplate中显示的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.