来自父类的公共对象在子类xaml中为null

时间:2018-05-01 14:16:12

标签: c# xaml uwp nullreferenceexception derived-class

考虑这个简单的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>

它的孩子 MyUserControl2.xaml 基本上只是从它衍生而来,没什么新东西:

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

现在让我们在某个地方使用孩子:

CustomControls.MyUserControl2 control = new CustomControls.MyUserControl2();
MyGrid.Children.Add(control);
control.MyTextBox.Text = "Some text";//NullReferenceException here

我得到NullReferenceException这基本上告诉我MyTextBox为空!这有什么不对?

P.S。

  1. 我给了这个问题足够的时间,我得出结论,当我从另一个视图派生xaml视图并尝试访问内部公共对象时会出现此问题。
  2. MyUserControl1.xamlMyUserControl2都有他们的代码隐藏 .cs 文件,他们只调用InitializeComponent(),没有别的。

1 个答案:

答案 0 :(得分:1)

通过咨询我的团队,简短的回答不受支持。

看起来您希望使用XAML进行可视继承,并在要使用的基本XAML文件中包含UI。对于XAML,这不是像Winforms那样支持的收件箱。以下是有关它的更多信息以及限制:UserControl inheritance #100

如果您在没有任何XAML的情况下创建用户控件完成代码,则子类应该可以正常工作。

相关问题