简体   繁体   中英

Attempting to get child control of currently selected tab

I'm attempting to get the TextEditor control off of the currently selected tab in my tab control. The tabs and text editors are created dynamically so simply referencing the text editor isn't an option. I've searched far and wide and so far, no answer has helped me.

The following code works for Winforms, but not WPF:

var currentTextEdit = tabControl.SelectedTab.Controls.OfType<TextEditor>().First();

Is there something along these lines that perhaps I'm missing?

This is how I'm creating each tab and adding a TextEditor control to each tab created:

TabControl itemsTab = (TabControl)this.FindName("tabControl");
TextEditor textEdit = new TextEditor();

Then to create the new tab and add the text editor:

TabItem newTab = new TabItem();
newTab.Content = textEdit;
itemsTab.Items.Add(newTab);

Further down in the code I get the currently selected tab like so:

TabItem ti = tabControl.SelectedItems as TabItem;

And using the GetChildOfType extension method, I'm attempting to get the current text editor like so:

var currentTextEditor = ti.GetChildOfType<TextEditor>();

This code returns the NullReferenceException:

File.WriteAllText(saveF.FileName, currentTextEditor.Text);

Indeed I wrote a not right thing in my comment. TabControl works in a little different way in comparing with other controls. It has a collection of TabItems . TabControl can show every header of each TabItem which belongs to its collection. At the same time TabControl "grabs" the selected TabItem's content and add it to its ContentPresenter (it is called PART_SelectedContentHost - just use ILSpy).

So, returning to your issue, you have to search for your TextEditor directly in the TabControl . Then you can use this code:

TabControl itemsTab = (TabControl)FindName("tabControl");
TextEditor currentTextEditor = itemsTab.GetChildOfType<TextEditor>();
if (currentTextEditor != null)
{
    File.WriteAllText(saveF.FileName, currentTextEditor.Text);
}

You should always check if the object you obtain from GetChildOfType<T> method is not null, since if GetChildOfType<T> cannot find a control whose type is T, it returns null.

As I told in my previous comment you can find here the code of GetChildOfType<T> .

I hope this answer can help you.

使用WPF时,我通常使用该方法

   var currentTextEdit = tabControl.SelectedTab.Children.OfType<TextEditor>().First();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM