I have a mainform which has a tabControl
. I am attempting to create a userControl
that can be added to a tabItem
.
I aim to add a tabControl
to the userControl
however I get this error:
'[Unknown]' property does not point to a DependencyObject in path '(0).(1)[1].(2)'.
The code is very simple within the userControl
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TabControl>
<TabItem>
</TabItem>
</TabControl>
</Grid>
How do I create the userControl
so that it can contain a tabControl
and then be added to the mainForm within a tabItem
?
CodePudding user response:
UserControl1.xmal
<UserControl x:Class="WpfApp1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TabControl x:Name="tabControl">
</TabControl>
</Grid>
</UserControl>
UserControl.cs
public partial class UserControl1 : UserControl
{
public List<TabItem> TabItem { get; set; } = new List<TabItem>();
public UserControl1()
{
InitializeComponent();
}
public override void OnApplyTemplate()
{
foreach (TabItem tabItems in TabItem)
tabControl.Items.Add(tabItems);
base.OnApplyTemplate();
}
}
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
Height="450" Width="800">
<Grid>
<local:UserControl1 Height="200" Width="200">
<local:UserControl1.TabItem>
<TabItem Header="Tab1">
<TextBox/>
</TabItem>
<TabItem Header="Tab2">
<TextBox/>
</TabItem>
</local:UserControl1.TabItem>
</local:UserControl1>
</Grid>
</Window>
In this case, the TextBox cannot be accessed through the x:Name="",
Because TextBox is a child of UserControl, not a child of MainWindow.