2

In my WinUI 3 app, I get no errors when the app is in Debug mode, but when I turn the Release mode, I get a System.NullReferenceException.

Looking at the stack it seems to me that the problem is related to the TreeView and the ItemsSource binding.

stack detail

Here is the XAML I use to produce the exception:

<?xml version="1.0" encoding="utf-8"?>
<Window
    x:Class="App1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="App1">

    <StackPanel Orientation="Vertical">
        <TreeView ItemsSource="{x:Bind Menu}" />
    </StackPanel>
</Window>

and the code behind:

namespace App1;

/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();
    }

    public ObservableCollection<MenuItemViewModel> Menu { get; set; } = new ObservableCollection<MenuItemViewModel>();
}

public class MenuItemViewModel
{
    public string Title { get; set; }
}

The Microsoft.WindowsAppSDK is Version="1.6.250228001"

I tried the following combinations of ItemsControl and collections:

  • TreeView+ ObservableCollection<>, the exception is raised in Release mode,

  • TreeView+ List<>, the exception is not raised

  • ListView + ObservableCollection<>, the exception is raised in Release mode,

  • ListView + List<>, the exception is not raised

What am I missing?

1
  • You could take a look at Andrew's solution about this. Commented Mar 25 at 7:09

1 Answer 1

1

It seems that you are hitting this.

Enabling AllowUnsafeBlocks:

<AllowUnsafeBlocks>true</AllowUnsafeBlocks>

or installing Microsoft.Windows.CSWinRT (v2.2.0 or later) NuGet package should fix your issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.