shady shady - 23 days ago 7
C# Question

Xamarin.Forms ViewModel in markup doesnt load dll

I'm trying to define a viewmodel class in the markup of my Xamarin.Forms App.xaml.

<xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:MyPCL.Client.ViewModels;assembly=MyPCL.Client"
x:Class="TestApp2.App">
<Application.Resources>
<viewModels:MainViewModel x:Key="MainViewModel"/>
</Application.Resources>
</Application>


I get this error:
Unhandled Exception:

System.IO.FileNotFoundException: Could not load file or assembly 'MyPCL.Client' or one of its dependencies.

but if i declare and initialize this class in my app.xaml.cs, it works fine. Why would this load in code behind but not in markup?

Answer

The Xamarin linker automatically tries to minimize the size of the app by removing libraries and classes that aren't referenced. Apparently declaring it in the XAML alone isn't enough to make the linker recognize that a reference exists (this may be a bug you should file with Xamarin). Adding a reference in App.xaml.cs forces the linker to retain it.

You can read more about the linker and its different settings here.

Comments