0

I am brand new to Avalonia and I have a UserControl with a custom Label. Every time I try to get/set on that UserControl I get a NullReferenceException. This only happens on my UserControls.

User Control

<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
             x:Class="Calendar.UserControls.IconButton">
    <Grid>
        <Label x:Name="TestLabel" Content="test" PointerEnter="OnPointerEnter"/>
    </Grid>
</UserControl>

User Control Code

private void OnPointerEnter(object? sender, PointerEventArgs e) {
    var text = TestLabel.Content; // NullReferenceException!
}

Why am I getting this null exception? This seems to work fine outside of Avalonia.

I tried

  • Getting/setting in the UserControl (produced the same error)
  • Using ((Label) sender).Content instead (works fine)
  • Getting/setting elements from MainWindow.axaml (works fine)
Kamoi
  • 11

1 Answers1

0

If you are not using Avalonia.NameGenerator you have to use FindControl<T> method to locate the control

private readonly Label testLabel;
...

testLabel = this.FindControl<Label>("TestLabel");
testLabel.PointerEnter += OnPointerEnter;
radoslawik
  • 915
  • 1
  • 6
  • 14