使用单个控件作为多个选项卡的内容

时间:2013-09-24 19:22:22

标签: c# wpf

我有一个TextBox,一个TabControl和一个名为someobject的简单对象。

我创建了一个List<someobject>对象,并用动态数字someobject填充它。

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

以下是我正在做的评论代码

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相同的结果吗?

这只是示范的一个例子。

0 个答案:

没有答案
相关问题