Xamarin

Multi-targeting the world: a single project to rule them all

January 4, 2017 Coding 5 comments , , , , , , ,

Multi-targeting the world: a single project to rule them all

Starting with Visual Studio 2017, you can now use a single project to build platform-specific libraries for all project types. This blog will explore why you might want to do this, how to do it and workarounds for some point-in-time issues with the tooling.

Contents

Intro

Since the beginning of .NET Core, the project.json format has enabled multi-targeting, that is compiling to multiple target frameworks in parallel and creating an output for each. With ASP.NET Core, it’s common to target both net45 and netcoreapp1.0 so you can deploy the site to either the desktop framework, which runs on Windows, or to the CoreCLR, which runs cross-platform. Multi-targeting is nothing more than compiling the same code multiple times, once per target platform. Each target can specify its own dependencies and ifdef‘s, so you can easily tailor the code to the specific platform.

Another example may have a library target netstandard1.0, netstandard1.3, and net45 to enable different levels of functionality based on the available surface area.

While it was also possible to target UWP, Win8, or profile-based PCL’s, using project.json, doing so required hacks like private copies of all reference assemblies, WinMD files and more. Beyond that, some things didn’t work correctly as some platforms require additional targets to generate additional outputs like .pri files on UWP for resource lookup. So while technically possible, full multi-targeting was brittle and required you to stay in a very narrow path, avoiding things like resources or GUI elements that require the full tool-chain to process.

Enter MSBuild

With the move to MSBuild as part of the .NET Core Tooling direction change, the picture gets much better, so much so that with VS 2017 RC2, you can correctly multi-target all platform types, including UWP, profile-based PCL’s, and Xamarin iOS/Android. Not only that, but by conditionally including/excluding directories based on globs, you can reduce the need for ifdef‘s in many cases.

As part of being open sourced and enabled to run cross-platform, the build targets and tasks required to actually do the build were combined into an SDK. This went along with drastic simplification of the csproj file to have a minimal footprint, that will get even smaller, like this:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.App" Version="1.0.1" />
  </ItemGroup>
</Project>

Microsoft’s blog details all of the improvements in this area. For current lack of a better term, I’ll call projects based on these new tools “SDK style.” The easiest way to identify these “SDK style” projects is by looking for the Sdk attribute in the top Project element.

Multi-targeting vs. .NET Standard Libraries vs. PCL’s

Before we go further, let’s answer this question that many people have asked — why would you want to multi-target vs just use a single portable library, whether that’s .NET Standard or an older profile-based PCL?

There are several answers to that question — first, if your code can all fit within a single .NET Standard-based library, then there’s no reason to multi-target. If you’re using a legacy profile-based PCL, at the very least consider moving up to the equivalent .NET Standard version. Don’t make more work for yourself. The decision to multi-target falls out of a need to use functionality that doesn’t exist within a .NET Standard version or if you need to target an earlier platform that doesn’t support the .NET Standard version you need. A common example is that many libraries still need to support .NET 4.5. Despite a significant amount of functionality available in .NET Standard 1.3, that .NET Standard version only supports .NET 4.6+. Chances are though that the code would work “just fine” on .NET 4.5, so it’s easy to multi-target to both net45 and netstandard1.3.

The other main reason why you’d need to multi-target is to use platform-specific code within your library. For example, on iOS you might want to use SecKeyChain for saved credentials, on Android use its Context to access shared services like preferences, and on Windows its Credential Manager. You might have a common method called GetCredential that other code uses to get the data. Today you might use dependency injection or reflection to access a “.Platform” library with a specific implementation that your common code uses. Instead, you can choose to multi-target and access the platform code directly.

How to multi-target

Let me start by saying that the methods here are based on the new “SDK-style” projects that VS 2017 provides. They orchestrate using the existing project types that are installed by Visual Studio. As such, the build itself won’t work on a box without the other tools installed (so you’re building on a Windows box, much like you probably are today). Some of these may work on a Mac with Visual Studio for Mac but I have not tested that in any way. When you install Visual Studio 2017, make sure to install all of the tools for the project types you need (Xamarin, UWP, etc) and also the .NET Core Tooling.

There’s no UI in VS for adding additional target frameworks, but I have some samples that show what to do.

First, create a new .NET Core Class Library project. If you don’t see the following option, make sure to install the .NET Core workload in the VS Installer.

New .NET Core Class Library
.NET Core workload

Right-click the project and select “Edit project file…”. This is new in VS 2017 – the ability to edit the project file while it’s open and have changes instantly reflected.

In the editor, after noticing how much less boilerplate code there is now, look for the TargetFramework property that looks like this: <TargetFramework>netstandard1.3</TargetFramework> property. Change that to <TargetFrameworks>netstandard1.3;net45</TargetFrameworks> to target .NET 4.5 and NET Standard 1.3. You can add however many targets you want by adding to that semi-colon list. It’s subtle, but note the difference in property names between TargetFramework and TargetFrameworks with a plural. It’s easy to miss.

For some frameworks, like .NET 4.5, that’s all you need to do. However, targeting .NET Standard and .NET 4.x is far from “the world.” We can do better! You would think it should be as easy as adding additional TFM’s like uap10.0, xamarin.ios10 or MonoAndroid70 to the list, and hopefully by the time the tools RTM it will be, but for now we need to add extra properties to the project file to tell MSBuild what to do with those.

Fortunately, and here’s the real secret, the “SDK-style” build system has a LanguageTargets property that you can specify per TFM to import the targets for that project type instead of the vanilla Microsoft.CSharp.targets import. That means we can use the “Windows Xaml”, Android, iOS, or any other platform tool-chain we need.

Xamarin Example

In the example here, I have a class library that multi-targets to net45, uap10.0, netstandard1.3, Xamarin.iOS10 and MonoAndroid70. In this contrived library, I have a Greeter class that’s calling a Hello() method that needs platform specific code. I’m using a pattern where I have a directory for each TFM where code in there only gets included there, so no ifdef‘s are needed. For Android, Resources are supported if you need them. While the example doesn’t currently use them, you could use PList‘s, xib‘s or Story Boards on iOS, Page‘s on UWP, or any other “native” file type supported by the platform.

Win81/WP8/PCL/Wpa81/Xamarin/Net45 Example

As a more realistic example, one of my libraries, Zeroconf, an mDNS discovery library, targets “the world.” It currently has concrete implementations for wp8, Wpa81, Win8, portable-Wpa81+Win81, uap10.0, net45, and netstandard1.3 (which supports Xamarin and CoreCLR.) In addition to the the concrete implementations, it provides a netstandard1.0 façade to support being used in portable libraries. The different concrete implementations are required due to differences in the networking stacks between the various Windows networking stacks. For now, the uap10.0 version cannot use the netstandard1.3 version until NetworkInformation is fully supported by the platform, so it continues to use the WinRT variant. You can see the platform-specific code in the platforms directory and then how they’re conditionally included by the csproj in the ItemGroups

The property groups at the top contain the LanguageTargets and properties needed. For portable-Wpa81+Win81 two extra items are required as the special PCL profile also supports WinRT. The ItemGroup here has two TargetPlatform to pull in the correct .winmd references.

Building

You can build the libraries either in VS 2017 or the command-line. If you use the command line, you’ll want to run the following from a VS 2017 Developer Command Prompt: msbuild /t:restore followed by msbuild /t:build. If you want to create a NuGet package, you can run msbuild /t:pack. It’s important to note that you must currently use msbuild, the desktop version in the VS 2017 path, to build these and not dotnet build. The reason is that while dotnet build calls MSBuild, it’s currently using a CoreCLR version even though the desktop version is present in your VS installation. The engineering team is aware of this and in the future, dotnet build will be smart enough to call the desktop version of msbuild when present. The “regular” targets file we’re using to support the platform-specific features are designed for Desktop MSBuild. They do not yet have support for CoreCLR tasks. Bottom line, as of the current release: if your targets use build tasks, then you need to provide both CoreCLR and Desktop versions of the library in order to support both “regular” MSBuild and dotnet build.

Common gotcha’s

There are several bugs in the tool-chain currently that are in the process of being fixed:

  • Some Project-to-project (p2p) references aren’t resolving correctly. Whereas they should resolve to the “best” match, they are resolving to the first TFM in the list.
  • Another bug is preventing a “legacy” csproj from doing a p2p reference with a “Portable Library can only reference other portable library” error.
  • Files that are conditionally included won’t show up in the Solution Explorer. As a workaround, include all files with None as the first item group (see example).
  • for iOS (and possibly Android), you need to set DebugType to full as the Xamarin ConvertPdb2Mdb task doesn’t yet support the new Portable PDB format generated by this tool-chain.
  • Win8, Win81, and uap10.0 aren’t correctly understood by the NuGet targets today. As a workaround, you need to include the NugetTargetMoniker property set to the full TFM as shown here. Similarly, for legacy PCL targets, it requires Version=v0.0 in the NugetTargetMoniker here. These should hopefully be fixed by GA.
  • Windows assemblies that use resources need a .pri file alongside them. They’re currently missing from the generated NuGet. Workaround is to use your own .NuSpec for now until the bug is fixed.

Into the weeds, how it all works

This is by no means an official explanation, it’s what I’ve found from exploring the SDK build targets. Some of the terminology and concepts may change over time.

The “SDK style” projects consist of a set of targets/tasks that are pre-installed with MSBuild (and the CLI tools). You can see them in the following directory: C:\Program Files (x86)\Microsoft Visual Studio\2017\<sku>\MSBuild\Sdks where <sku> is Community, Professional, or Enterprise, depending on what you installed. The two SDK’s you’re likely to use directly are Microsoft.NET.Sdk and Microsoft.NET.Sdk.Web.

The Sdk attribute causes an Sdk.props and Sdk.targets within the specified SDK’s \Sdk directory to be imported before and after the project file. The Microsoft.NET.Sdk SDK’s targets defines an “outer” and “inner” build. The “outer-loop” is what your project file directly defines, including several TFM’s in the TargetFrameworks property. If you only have a single build with a TargetFramework property defined, then there’s only an “inner-loop”.

For an “outer-loop” build, the SDK targets imports props/targets in a buildCrossTargeting directory (soon to be renamed to buildMultiTargeting). Those get auto-included before and after the main project file (props before, targets after.) The “outer-loop” targets will eventually loop through each of the TargetFrameworks calling msbuild again in an “inner-loop” with TargetFramework set to one TFM. This “inner-loop” build is what we currently have in today’s “normal” project types. The “inner-loop” build provides an extension point for providing your language-specific targets (the Import that was at the bottom of your old csproj before) in place of the “vanilla” one it’ll include by default. By providing a LanguageTargets property for the “inner-loop,” conditioned by TFM, we can use the “original” targets that invoke the full tool-chain for the target platform. See here, here and here for UWP, iOS, and Android, respectively.

Within each conditionally defined property group, we can set properties that are specific to a particular “inner-loop.” These correspond to the properties in your existing platform-specific project file and are used by the platform-specific targets specified.

One thing you give-up currently is any UI in VS for configuring these properties. Perhaps they’ll return sometime in the future. For now, one thing I’ve found helpful is to maintain a few “dummy” projects where I can edit some settings to see the values and then put them into my multi-targeting csproj.

Looking forward

As of today (January 4, 2017), the tooling is in a fairly rough state. The .NET Core tooling is rightfully in an “alpha” state. The MSBuild SDK is under active development and things will change before GA. There are a number of issues in the tooling that can make it hard to use today, but I expect those to be fixed soon. Most of the bugs I’ve found are slated to be fixed in the RC3 time-frame, and I’d expect things to be better with that release.

As to whether-or-not to take the plunge today: I’d suggest that if you have a tolerance for figuring this out and reporting issues you’ll encounter, then go for it. If you have a complex project today that already multi-targets a different way (most likely by using multiple “head” projects and shared code project types), I would recommend trying this out in a branch to see how far you get. I’ll be happy to help, just give me a shout. The more the community bangs on this stuff up front, the more issues can be addressed prior to GA.

Acknowledgments

Many thanks to Brad Wilson, Joe Morris, and Daniel Plaisted for reviewing this post and providing feedback.

Using Xamarin Forms with .NET Standard

July 9, 2016 Coding 10 comments , , , ,

Using Xamarin Forms with .NET Standard

With the release of .NET Core and the .NET Standard Library last week, many people want to know how they can use packages targeting netstandard1.x with their Xamarin projects. It is possible today if you use Visual Studio; for Xamarin Studio users, support is coming soon.

Prerequisites

Using .NET Standard pretty much requires you to use project.json to eliminate the pain of “lots of packages” as well as properly handle transitive dependencies. While you may be able to use .NET Standard without project.json, I wouldn’t recommend it.

You’ll need to use the following tools:

Getting Started

As of now, the project templates for creating a new Xamarin Forms project start with an older-style packages.config template, so whether you create a new project or have an existing project, the steps will be pretty much the same.

Step 1: Convert your projects to project.json following the steps in my previous blog post.

Step 2: As part of this, you can remove dependencies from your “head” projects that are referenced by your other projects you reference. This should simplify things dramatically for most projects. In the future, when you want to update to the next Xamarin Forms version, you can update it in one place, not 3-4 places. It also means, you only need the main Xamarin.Forms package, not each of the packages it pulls in.

If you hit any issues with binaries not showing up in your bin directories (for your Android and iOS “head” projects), make sure that you have set CopyNuGetImplementations to true in your csproj as per the steps in the post.

At this point, your project should be compiling and working, but not yet using netstandard1.x anywhere.

Step 3: In your Portable Class Library projects, find the highest .NET Standard version you need/want to support.

Here’s a cheat sheet:

  • If you only want to support iOS and Android, you can use .NET Standard 1.6. In practicality though, most features are currently available at .NET Standard 1.3 and up.
  • If you want to support iOS, Android and UWP, then NET Standard 1.4 is the highest you can use.
  • If you want to support Windows Phone App 8.1 and Windows 8.1, then NET Standard 1.2 is your target.
  • If you’re still supporting Windows 8, .NET Standard 1.1 is for you.
  • Finally, if you need to support Windows Phone 8 Silverlight, then .NET Standard 1.0 is your only option.

Once you determine the netstandard version you want, in your PCL’s project.json, change what you might have had:

{
    "dependencies": {
        "Xamarin.Forms": "2.3.0.107"        
    },
    "frameworks": {        
        ".NETPortable,Version=v4.5,Profile=Profile111": { }
    },
    "supports": { }
}

to

{
    "dependencies": {
        "NETStandard.Library": "1.6.0",
        "Xamarin.Forms": "2.3.0.107"        
    },
    "frameworks": {        
        "netstandard1.4": {
            "imports": [ "portable-net45+wpa81+wp8+win8" ]
         }
    },
    "supports": { }
}

Note the addition of the imports section. This is required to tell NuGet that specified TFM is compabtible here beause the Xamarin.Forms package has not yet been updated to use netstandard directly.

Then, edit the csproj to set the TargetFrameworkVersion element to v5.0 and remove any value from the TargetFrameworkProfile element.

At this point, when you reload the project, it should restore the packages and build correctly. You may need to do a full clean/rebuild.

Seeing it in action

I created a sample solution showing this all working over on GitHub. It’s a good idea to clone, build and run it to ensure your environment and tooling is up-to-date. If you get stuck converting your own projects, I’d recommend referring back to that repo to find the difference.

As always, feel free to tweet me @onovotny as well.

Xamarin MVP

January 25, 2016 Coding No comments

Xamarin MVP

Xamarin just announced their newest round of MVP awards, and I am very honored to have received one. I have always thought that the C# and .NET are the best, most productive, way to create applications for iOS and Android and Xamarin’s tools make this possible.

Hope to see you at Xamarin Evolve later this April!

xUnit for Xamarin is dead, long live xUnit for Devices!

March 16, 2015 Coding 1 comment , ,

xUnit for Xamarin is dead, long live xUnit for Devices!

In conjunction with today’s release of xUnit 2.0 RTM, I’m happy to announce the initial release of xUnit for Devices (GitHub | NuGet). This has been a long time coming and I’d like to thank Brad Wilson and James Newkirk for their tremendous efforts over the years.

Project rename

xUnit for Devices started out as xUnit for Xamarin. Over the course of development however, it became apparent that what we really have is an MVVM-based test runner where the view was only an implementation detail. Current support is limited to platforms Xamarin Forms supports, but in the future it’s pretty easy to add a desktop/WPF view and support any additional GUI platform as needed.

Upgrading your projects to RTM

If you’ve been using xUnit for Xamarin, the easiest way to update is by using NuGet. There’s a final xunit.runner.xamarin package that pulls in the new xunit.runner.devices package. After upgrading, you can simply remove the old package and keep the dependencies. Windows Phone 8 users will need to make one additional change in the MainPage.xaml to update the assemly name from xunit.runner.xamarin to xunit.runner.devices.

Getting Started

The RTM 1.0 release is available on NuGet and on GitHub.

For iOS and Android, create a new blank Xamarin app project to host the unit test runner. Make sure to give any capabilities/permissions you need in the appropriate manifest.

For WP8, create a new Unit Test Project and then remove the MSTestFramework reference.

Then for all platforms, install/update the xunit.runner.devices package via the GUI or Package Manager Console:
Install-Package xunit.runner.devices

Then look for the .cs.txt, xaml.txt files that are the templates for your platform and copy/paste the contents into the app. Specifically,
– iOS: replace the contents of AppDelegate.cs with AppDelegate.cs.txt
– Android: replace the contents of MainActivity.cs with MainActivity.cs.txt
– WP8: replace the contents of MainPage.xaml.cs with MainPage.xaml.cs.txt and MainPage.xaml with MainPage.xaml.txt

xUnit Device Runners 1.0 RC3

February 23, 2015 Coding 1 comment , ,

Following the release of xUnit 2.0 RC3, the Xamarin Device Runners have been updated to work with RC3.

One note for Android users: due to a dependence on Xamarin Forms, your runner app project needs to use API level 21 as its target and SDK. You can target down to API level 15 if you wish. You can also reference other MonoAndroid or Portable Class Libraries if you want to keep your unit tests at a different API level. You also might need to specify a default theme on some devices to workaround a different Xamarin Forms bug. Please see the updated MainActivity.cs.txt for the specifics.

Wait, what happened to RC2?

If you blinked, you missed it. RC2 of the Device Runners came out Saturday. With xUnit RC3 being a quick update from RC2, it’s best to skip to the latest.

As always, if you run into any issues, feel free to reach out to @onovotny on Twitter or post an issue on GitHub.

Getting Started

RC3 is available on NuGet and on GitHub.

For iOS and Android, create a new blank Xamarin app project to host the unit test runner. Make sure to give any capabilities/permissions you need in the appropriate manifest.

For WP8, create a new Unit Test Project and then remove the MSTestFramework reference.

Then for all platforms, install/update the xUnit.Runner.Xamarin package via the GUI or Package Manager Console:
Install-Package xunit.runner.xamarin -Pre

Then look for the .cs.txt, xaml.txt files that are the templates for your platform and copy/paste the contents into the app. Specifically,
– iOS: replace the contents of AppDelegate.cs with AppDelegate.cs.txt
– Android: replace the contents of MainActivity.cs with MainActivity.cs.txt
– WP8: replace the contents of MainPage.xaml.cs with MainPage.xaml.cs.txt and MainPage.xaml with MainPage.xaml.txt

Announcing: xUnit Device Runner RC1

January 31, 2015 Coding 1 comment , , , ,

xUnit Device Runner 1.0 RC1

I’m pleased to announce the release of the xUnit Device Runners Release Candidate 1. This release adds support for the Xamarin.iOS Unified profile, required for all new iOS applications now and updates starting in July.

Other notable enhancements include a filter for searching test cases by name and status (pass/fail/not run).

To get started, please see the following posts:

If you run into any issues, please file a report in the issue tracker.

Xamarin 3.9 is Stable: Update Now

January 12, 2015 Coding 1 comment

Xamarin just pushed 3.9 to the stable channel. I’d recommend everyone doing Xamarin work update to this. The most important updates are:

  1. Support for creating 64-bit iOS apps. This uses the new “Xamarin.iOS Unified” profile. The existing profile has been deprecated but will remain for legacy enterprise-only apps. As of Feb 1, Apple will require new apps to be 64-bit and as of June 1, updates to existing apps must be 64-bit.
  2. Support for Visual Studio 2015 Preview. For those of you using the VS 2015 preview, Xamarin 3.9 supports it.
  3. Visual Studio Android Emulator support. The VS Android emulator uses Hyper-V, so it’s fast and also works if you had to enable HyperV for any other reason and thus can’t use Genymotion or other ring 0-based virtualization.

DataTemplateSelector for Xamarin.Forms

December 31, 2014 Coding 4 comments , ,

Next up in the saga of Xamarin Forms: DataTemplateSelector‘s.

For people coming into Xamarin Forms from Microsoft XAML, it’s easy to see many gaps. Xamarin Forms is still young, but there are some workarounds. I’ve already blogged about how to implement a ContentPresenter, next up is the DataTemplateSelector.

Supposed you want to put a list of items into a ListView but use a different DataTemplate for some of the items? In Microsoft XAML, you could set the ItemTemplateSelector property to a custom DataTemplateSelector and you’d be all set. Sadly, this is not yet available within Xamarin Forms, but we can create our own.

To see the specific usage/examples of how to implement a custom DataTemplateSelector instance, please refer to MSDN or your favorite search engine. Usage will be exactly the same*

There are a few classes we’ll need:

  1. DataTemplateSelector.cs
    public class DataTemplateSelector
    {
        public virtual DataTemplate SelectTemplate(object item, BindableObject container)
        {
            return null;
        }
    }
    
  2. ExtendedlistView.cs
    public class ExtendedListView : ListView
    {
        public static readonly BindableProperty ItemTemplateSelectorProperty = BindableProperty.Create("ItemTemplateSelector", typeof(DataTemplateSelector), typeof(ExtendedListView), null, propertyChanged: OnDataTemplateSelectorChanged);
        private DataTemplateSelector currentItemSelector;
        private static void OnDataTemplateSelectorChanged(BindableObject bindable, object oldvalue, object newvalue)
        {
            ((ExtendedListView)bindable).OnDataTemplateSelectorChanged((DataTemplateSelector)oldvalue, (DataTemplateSelector)newvalue);
        }            
        protected virtual void OnDataTemplateSelectorChanged(DataTemplateSelector oldValue, DataTemplateSelector newValue)
        {
            // check to see we don't have an ItemTemplate set
            if (ItemTemplate != null && newValue != null)
                throw new ArgumentException("Cannot set both ItemTemplate and ItemTemplateSelector", "ItemTemplateSelector");
            currentItemSelector = newValue;
        }
        protected override Cell CreateDefault(object item)
        {
            if (currentItemSelector != null)
            {
                var template = currentItemSelector.SelectTemplate(item, this);
                if (template != null)
                {
                    var templateInstance = template.CreateContent();
                    // see if it's a view or a cell
                    var templateView = templateInstance as View;
                    var templateCell = templateInstance as Cell;
                    if (templateView == null && templateCell == null)
                        throw new InvalidOperationException("DataTemplate must be either a Cell or a View");
                    if (templateView != null) // we got a view, wrap in a cell
                        templateCell = new ViewCell { View = templateView };
                    return templateCell;
                }
            }
            return base.CreateDefault(item);
        }
        public DataTemplateSelector ItemTemplateSelector
        {
            get
            {
                return (DataTemplateSelector)GetValue(ItemTemplateSelectorProperty);
            }
            set
            {
                SetValue(ItemTemplateSelectorProperty, value);
            }
        }
    }
    

With these two pieces, you can now create your own selector. Suppose you have an RSS Feed that you want to display an alternate template every 4 items. For this example, we’ll assume that each item in the list has an index attached.

We’ll start with our custom selector:

public class NewsItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate NewsItem { get; set; }
    public DataTemplate NewsItemLarge { get; set; }

    public override DataTemplate SelectTemplate(object item, BindableObject container)
    {
        // must have IListItems
        var li = (IListItem)item;

        if (li.Index == 0 || li.Index%4 == 0)
        {
            return NewsItemLarge;
        }
        return NewsItem;
    }
}

Now in the App.xaml, lets add our templates. (Aside: See this example for how to use XAML for your App class allowing you to easily use XAML shared resources.)

  <DataTemplate x:Key="NewsItem">
    <Grid MinimumHeightRequest="320">
      <Grid.RowDefinitions>
        <RowDefinition Height="120"/>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="140"/>
        <ColumnDefinition Width="*"/>
      </Grid.ColumnDefinitions>
      <Image Grid.Row="0" Grid.Column="0" Source="{Binding ImageUrl}" HeightRequest="110" Aspect="AspectFill" VerticalOptions="Start" />
      <StackLayout Grid.Row="0" Grid.Column="1" Padding="16, 0, 10, 8">
        <Label Grid.Row="0" Grid.ColumnSpan="2" VerticalOptions="Center" Text="{Binding Title}" />
        <ContentView HeightRequest="4" /><!-- Hack for margin -->
        <Label Grid.Row="1" Grid.Column="1" VerticalOptions="Start" Text="{Binding Summary}" />
      </StackLayout>
    </Grid>
  </DataTemplate>

  <DataTemplate x:Key="NewsItemLarge">
    <Grid MinimumHeightRequest="520">
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="120" />
      </Grid.RowDefinitions>
      <Image Grid.Row="0" Source="{Binding ImageUrl}" HeightRequest="400" Aspect="AspectFill" VerticalOptions="Start" />
      <StackLayout Grid.Row="1" Padding="16, 0, 10, 8">
        <Label Grid.Row="0" Grid.ColumnSpan="2" VerticalOptions="Center" Text="{Binding Title}" />
        <ContentView HeightRequest="4" />
        <!-- Hack for margin -->
        <Label Grid.Row="1" Grid.Column="1" Style="{StaticResource ItemSubheaderText}" VerticalOptions="Start" Text="{Binding Summary}" />
      </StackLayout>
    </Grid>
  </DataTemplate> 

Here’s the custom DataTemplateSelector:

public class NewsItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate NewsItem { get; set; }
    public DataTemplate NewsItemLarge { get; set; }

    public override DataTemplate SelectTemplate(object item, BindableObject container)
    {
        // must have IListItems
        var li = (IListItem)item;

        if (li.Index == 0 || li.Index%4 == 0)
        {
            return NewsItemLarge;
        }
        return NewsItem;
    }
}

Finally, we’ll add an instance of the DataTemplateSelector to the App.xaml:


<controls:NewsItemTemplateSelector 
  x:Key="NewsItemTemplateSelector"
  NewsItem="{StaticResource NewsItem}"
  NewsItemLarge="{StaticResource NewsItemLarge}" 
/>

Later on, when we want to use it, we can use it with our ExtendedListView:


<controls:ExtendedListView 
  ItemsSource="{Binding Items}"
  ItemTemplateSelector="{StaticResource NewsItemTemplateSelector}">
</controls:ExtendedListView>

When rendered, the first item will have the large image template and then every fourth item will too.

BONUS: You can use either View or Cell-derived types in your DataTemplates as the control will automatically wrap Views into a ViewCell.

Enjoy!

*probably.

ContentPresenter for Xamarin.Forms

December 31, 2014 Coding 4 comments , ,

While working on a new Xamarin Forms project, I came across the need for a ContentPresenter ala Microsoft XAML. The basic idea is to use a placeholder for a piece of content (usually a ViewModel) and then supply a DataTemplate to control how it should be displayed.

A simple example might look like this:


<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <controls:ContentPresenter Grid.Row="1"
               BindingContext="{Binding MyModel, Source={StaticResource Locator}}" 
               ItemTemplate="{StaticResource MyModelTemplate}"
               />

</Grid>

This goes back to some of the more “classic” MVVM patterns where we want to make our display more componentized.

In Xamarin Forms Today (v1.3.0), if you want to create a custom component, you can derive from ContentView and go to town. Add your widgets either with XAML or in code. Many times though, we don’t really need to create a new class/view directly. A DataTemplate is sufficient as we can bind to the ViewModel and use Commands to take action. These are the so-called “zero code-behind” views.

In this case, a ContentPresenter is all we need – set the BindingContext to your ViewModel and create/bind a DataTemplate. New to Forms 1.3, you can now put resources in the Application-level, so you can more easily share those instances.

Here’s the complete code, sans-usings, to implement your own. This can go either in a Shared code or PCL:

public class ContentPresenter : ContentView
{
    public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create("ItemTemplate", typeof(DataTemplate), typeof(ContentPresenter), null, propertyChanged: OnItemTemplateChanged);

    private static void OnItemTemplateChanged(BindableObject bindable, object oldvalue, object newvalue)
    {
        var cp = (ContentPresenter)bindable; 

        var template = cp.ItemTemplate;
        if (template != null)
        {
            var content = (View)template.CreateContent();
            cp.Content = content;
        }
        else
        {
            cp.Content = null;
        }
    }

    public DataTemplate ItemTemplate
    {
        get
        {
            return (DataTemplate)GetValue(ItemTemplateProperty);
        }
        set
        {
            SetValue(ItemTemplateProperty, value);
        }
    }
}

If you want, you can get fancy with Triggers and change the ItemTemplate to vary based on whatever conditions you want.

Beware: Xamarin beta channel is borked!

September 12, 2014 Coding No comments

Here’s the core issue: Xamarin’s QA screwed up with the beta channel on Windows. If you use any portable class libraries in your projects (even if not at all Xamarin related!), VS will fail to load them due to a Xamarin bug. This is pretty poor and should never have made it to beta.

That said, if you want to use Xcode 6, you need to use Xamarin.iOS 8 on your Mac. Problem is that the stable version of Xamarin for VS won’t work with that…needs the matching beta. If you try to use Xcode 6 with the stable Xamarin.iOS, it can’t debug…so bam.

I’m sure this will be cleared up very shortly, but you might want to refrain from either installing Xcode 6 on your Mac or using the Xamarin beta channels for the next several days. Version 3.6.197 on Windows is the bad one….they say it’s fixed already, so the question is how quickly can the push an update out.