Search code examples
c#xamlmaui

Using an external library in XAML for .net Maui


I'm learning .net Maui by creating a MVVM application. I have a DataModel library external to the .net Maui application which contains the datamodels for data being passed between the Azure functions and the local app. That way, the models always stay in sync between applications and they only have to changed/updated once in code.

There is a project reference set for the DataModels library in the application.

However, while I can link and access the DataModels library in the C# code, I can't seem to get it to link in the XAML side.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="LicenseApp.MainPage"
         xmlns:viewmodel="clr-namespace:LicenseApp.ViewModels"
         xmlns:dms="clr-namespace:TestApp.DataModels"
         xmlns:dms2="clr-namespace:DataModels;assembly=DataModels"
         x:DataType="viewmodel:MainViewModel">

I've also tried:

xmlns:dms2="clr-namespace:MyModels.DataModels;assembly=DataModels"

xmlns:dms resolves to a local DataModels folder in the app which does work. However, I don't want the DataModels in this application.

xmlns:dms2 gives the error:

Error   XLS0419 Undefined CLR namespace. The 'clr-namespace' URI refers to a namespace 'DataModels' that could not be found.    

The code hinting doesn't come up with the library.

For what it's work, this is the code that is attempted to call the library here:

        <CollectionView Grid.Row="2" Grid.ColumnSpan="3" ItemsSource="{Binding Items}" SelectionMode="None">
        <CollectionView.ItemTemplate>
            <DataTemplate x:DataType="dms2:Customer">

The DataModels library compiles into "DataModels.dll". The customer DataModel looks like this:

namespace MyModels
{
    public static class Customer
    {
        public int Id { get; set; } 
        public DateTime Created { get; }
        public DateTime Updated { get; }
        public string? CustomerName { get; set; }
        public string? CustomerPhone { get; set; }
        public string? CustomerEmail { get; set; }
        public string? CustomerGuid { get; }
    }
}

What am I doing wrong? This should be possible, shouldn't it?


Solution

  • I found the problem...

    In my DataModels library, I had:

        public static class Customer
        {
           ....
        }
    

    This was not resolving in my xaml file but it was able to resolve in the code.

    Once I remove the "static" from the declaration, the code hinting found the class and assembly. Everything compiled ok after.