Consider this simple UserControl
MyUserControl1.xaml:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Test.CustomControls.MyUserControl1"
x:Name="control" Width="250" Height="100">
<Grid x:Name="MyGrid" x:FieldModifier="public">
<TextBlock x:Name="MyTextBox" x:FieldModifier="public" Text="Hello from the other side !!" FontWeight="Light" Foreground="red"/>
</Grid>
</UserControl>
and it's child MyUserControl2.xaml which basically just derive from it, nothing new:
<local:MyUserControl1
x:Class="Test.CustomControls.MyUserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test.CustomControls">
</local:MyUserControl1>
now let's use the child somewhere:
CustomControls.MyUserControl2 control = new CustomControls.MyUserControl2();
MyGrid.Children.Add(control);
control.MyTextBox.Text = "Some text";//NullReferenceException here
and I get NullReferenceException
which basically inform me that MyTextBox
is null !! What is wrong here?
P.S.
MyUserControl1.xaml
and MyUserControl2
has their code-behind .cs files and they just call InitializeComponent()
, nothing else.By consulting with my team, the short answer is not supported.
It looks like you are wanting to do visual inheritance with XAML with having UI inside the base XAML file to be used. For XAML, this is not a supported in-box like it was possible for Winforms
. Here is more information on it along with the restrictions:UserControl inheritance #100.
If you are creating the user control completed code behind without any XAML, the subclass should work well.