Can anyone explain how to get the control specified in the DataTemplate
when the tabs are added at run-time and the TabControl
has been customized in XAML to use plain class as data source? Here is the scenario.
I have a class
public class TabContent
{
public string Header { get; set; }
public string Code { get; set; }
public bool Modified { get; set; }
}
Here is the XAML customization of TabControl
:
<TabControl x:Name="tabControl" SelectionChanged="tabControl_SelectionChanged">
<!-- Header -->
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="txtHeader" Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<!-- Content -->
<TabControl.ContentTemplate>
<DataTemplate>
<!-- Code -->
<ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible">
<DockPanel>
<ListBox x:Name="lbLines" Width="Auto"
Margin="2,3.1,2,2"
FontFamily="Consolas"
HorizontalContentAlignment="Right">
<!-- ...snip.. -->
</ListBox>
<TextBox x:Name="editor"
Text="{Binding Code}"
AcceptsReturn="True" AcceptsTab="True"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
FontFamily="Consolas">
</TextBox>
</DockPanel>
</ScrollViewer>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
And, here is the text in code behind:
ObservableCollection<TabContent> _tabContents = new ObservableCollection<TabContent>();
//In constructor..
public MainWindow() {
tabControl.ItemsSource = _tabContents;
}
void loadTab() {
var t = new TabContent()
{
Header = "Code File 1",
Code = File.ReadAllText(@"C:\code.txt")
};
_tabContents.Add(t);
tabControl.SelectedItem = tabControl.Items[tabControl.Items.Count - 1];
}
Now, when user clicks on a tab, I want to get the textbox control in it.
private void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//how do I get the "editor" textbox and "lbLines" ListBox objects ???
}
=================
Why MSDN method doesn't work here: http://msdn.microsoft.com/en-us/library/bb613579(v=vs.110).aspx
The items in the TabControl are of type TabContent and not TabItem. So, the MSDN example fails to fetch the control as it doesn't meet the criteria: "in order to fetch the control, the template must be applied to the item." Here, TabContent is plain class, and cannot have template applied on it.