Search code examples
c#xamluwpnullreferenceexceptionderived-class

public object from parent class is null in child class xaml


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.

  1. I gave enough time to this problem and I concluded that this problem occurs when I derive a xaml view from another view and try to access the inner public objects.
  2. Both the MyUserControl1.xaml and MyUserControl2 has their code-behind .cs files and they just call InitializeComponent(), nothing else.

Solution

  • 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.