В моем проекте я динамически открываю и закрываю вкладки с помощью элемента управления вкладками. Содержимое каждой вкладки определяет DataTemplate в TabControl.Resources. Сам TabControl имеет свой ItemsSource, привязанный к ObservableCollection, где каждый раз, когда я добавляю новую вкладку, пользовательский интерфейс обновляется до соответствующего типа вкладки и ее правильного содержимого.
Я сохранил только то, что, по моему мнению, имеет отношение к приведенному ниже коду:
Код: Выделить всё
Код: Выделить всё
//Observable Collection to store the dynamically created tabs
ObservableCollection tabs = new ObservableCollection();
public MainWindow()
{
InitializeComponent();
tabControl.DataContext = tabs;
CreateTeamTab();
AccessContent();
}
private void CreateTeamTab()
{
//creates a new tabitem that i can populate with the data that i need
TabItem tb = new TabItem();
//creates the header
tb.Header = "Create Team";
//places the contents from the Tabcontrol.resources into the content of the tab.
tb.ContentTemplate = tabControl.FindResource("CreateTeamTab") as DataTemplate;
//adds the tab to the Observable Collection
tabs.Add(tb);
tabControl.SelectedItem = tb;
}
public void AccessContent()
{
//Down here I want to be able to access the content of the tab I just created (or any tab in the tabControl for that matter)
//And if it helps, I'd specifically like to access the TeamIdTextbox from the tab I just created
}
Я пробовал:
Код: Выделить всё
TabItem currentTab = (TabItem)tabControl.SelectedItem;
TextBox textbox = (TextBox)currentTab.FindName("TeamIdTextbox");
Я также пытался получить контент с помощью currentTab.Content
Я сделаю это скажем, одна вещь, которая ДЕЙСТВИТЕЛЬНО работала, заключалась в следующем: в одном из событий мне передали кнопку в качестве отправителя, и я сделал это, чтобы получить доступ к нужному мне элементу:
Код: Выделить всё
Button button = (Button)sender;
//gets the parent of the button
DockPanel dockPanel = (DockPanel)button.Parent;
//gets the parent of the dockpanel
Grid grid = (Grid)dockPanel.Parent;
//Finds the textbox
TextBox textBox = (TextBox)grid.FindName("PNameTextbox");
Наконец, я еще не пробовал использовать привязку для текстового поля. Однако по причинам, объяснение которых заняло бы слишком много времени, я бы предпочел не использовать привязку, поэтому было бы неплохо использовать что-нибудь еще.
Надеюсь, я предоставил достаточно подробное описание. Любая помощь будет принята с благодарностью. Спасибо

Подробнее здесь: https://stackoverflow.com/questions/783 ... rol-in-wpf