1

我有一个TextBox,一个TabControl和一个简单的对象,叫做someobject.

我创建一个List<someobject>对象并用动态数量的someobject.

Foreachsomeobject在该列表中,我创建了一个TabItem与其名称相同的值,该值与该列表中的 name 属性相同someobject

这是我在做什么的注释代码

public partial class MainWindow : Window
{

    List<SomeObject> list;
    TextBox textbox = new TextBox() { Name = "textbox1" };
    public MainWindow()
    {
        InitializeComponent();
        //create a test list of someobject
        list = new List<SomeObject>()
        {
            new SomeObject() {name = "Italian", description = "Italian description"},
            new SomeObject() {name = "German", description = "german description"},
            new SomeObject() {name = "French", description = "french description"}
        };

        //add a tab item for each object
        foreach(SomeObject someobj in list)
        {
            tabControl1.Items.Add(new TabItem { Name = someobj.name,Header = someobj.name });
        }

    }

    //on selected tabitem changed event set the content of all tab items to null and set the content of the selected tabitem to the TextBox textbox1
    private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        foreach(TabItem tab in (sender as TabControl).Items)
        {
            tab.Content = null;
        }
        string someobjectnameproperty = ((sender as TabControl).SelectedItem as TabItem).Name;
        textbox.Text = list.Find(obj => obj.name == someobjectnameproperty).description;
        ((sender as TabControl).SelectedItem as TabItem).Content = textbox;
    }

    //someobject class
    class SomeObject
    {
        public string name { get; set; }
        public string description { get; set; }
    }

}

我做了上述所有操作,因为我不想在每个选项卡项中都有一个文本框控件,代码运行良好,但是有没有更方便的方法来实现与 wpf 相同的结果?

这只是一个演示示例。

4

0 回答 0