Tuesday, September 5, 2017

Using .net Standard 2.0 with Xamarin Forms

Standard Libraries are replacing Portable Class Libraries.  Here is how to start using them in Xamarin Forms projects today.

To Start with create a new Xamarin forms app that uses a Portable Class Library



Since UWP will nor support .net Standard Libraries for a few months I would press cancel if you get the dialog asking what version of UWP you want to support.

Right click on the solution and select add new project.  Add a class library (.net standard)



Now drag the files App.Xaml and MainPage.Xaml from the PCL to the new class library.  You can also delete the file Class1.cs in the standard library we  created.

Open the properties for the Standard class library and change the default namespace to be the same as the portable class libraries



Time to add a NuGet package to the standard class library.  Microsoft.NetCore.Portability.Compatibility.  This will help prevent some build errors



Remove the portable class library from the solution.  Right click on the solution and select mange NuGet packages for the solution.  Select Updates and find Xamarin Forms.  Select the latest pre release and make sure the standard library is checked.  The latest prerelease supports standard libraries




Right click on the standard class library and select edit csproj.  Remove the following lines from the file.


  <ItemGroup>
    <EmbeddedResource Include="App.xaml">
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
    </EmbeddedResource>
    <EmbeddedResource Include="MainPage.xaml">
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
    </EmbeddedResource>
  </ItemGroup>

Save the file and add a reference in the android and ios project to the new standard library

Now you can run it

Here is what it looks like in the android emulator




In the next post in this series we will call a web service and save the json we get back to a file on the device.

1 comment: