All posts tagged xamarin

Post originally appeared at:

https://visualstudiomagazine.com/articles/2017/09/06/free-xamarin-book.aspx?m=1

 

Microsoft has been publishing a series of free eBooks and accompanying blog posts providing guidance about .NET application architecture best practices, with the latest focusing on Xamarin.Forms patterns.

Previous guidance addressed microservices architecture, containerized Docker apps and modern Web apps with ASP.NET and Microsoft Azure. The guidance consists of detailed eBooks, end-to-end reference architecture applications used as examples and blog posts that can help developers get a gist of the guidance and decide if they want to dig deeper with an eBook and reference application.

The new guide, “Enterprise Application Patterns Using Xamarin.Forms,” includes source code for a container-based eShop that extends the previous microservice/containers scenario. It includes the following functionality:

  • Authenticating and authorizing with a back-end service.
  • Browsing a catalog of shirts, coffee mugs and other marketing items.
  • Filtering the catalog.
  • Ordering items from the catalog.
  • Viewing the user’s order history.
  • Configuring settings.

“Guidance is provided on how to implement MVVM, dependency injection, navigation, validation and configuration management while maintaining loose coupling,” Microsoft said in a blog post. “In addition, there’s also guidance on performing authentication and authorization with IdentityServer, accessing remote data from containerized microservices, and unit testing.”

Developers don’t have to create the full-blown implementation that consumes back-end services from containerized microservices, however. They can just consume mock data services if they aren’t interested in how to deploy fully functional back-end services.

Written by David Britch, the 91-page book reportedly provides a comprehensive solution for Business-to-Employee (B2E), Business-to-Business (B2B) and Business-to-Consumer (B2C) apps that can share code across all target platforms — iOS, Android and the Universal Windows Platform (UWP) — and help lower the total cost of ownership (TCO).

 

The entire series of eBook guides are available on Microsoft’s .NET Application Architecture site. The new Xamarin.Forms offering can be downloaded here (note that this link triggers an automatic download).

While primarily targeting an audience of developers interested in learning how to design and create cross-platform enterprise apps, the book says it can also serve to help technical decision-makers choose an appropriate approach for creating such apps.

The post originally appeared at:

Developers can use Effects in Xamarin Forms to customize native controls and add some styling of their own. But why not simply use a custom renderer to achieve the same thing? While that is certainly possible there are some benefits to Effects.

Why would you use Effects?

Contrary to a custom renderer that always targets controls of a specific type an effect can be re-used throughout your app. Another advantage is that you can parameterize your effects with additional data. Most people use effects to simply change properties of a native control that aren’t yet made available through the existing Xamarin Forms controls. Effects work by attaching/detaching them to/from a Xamarin Forms control.

To get a quick idea of how that looks in XAML:

<Entry Text=This entry is awesome! TextColor=White HeightRequest=100 VerticalOptions=Center HorizontalOptions=Fill>
<Entry.Effects>
<local:CatEffect />
</Entry.Effects>
</Entry>
view rawCatEffect.xaml hosted with ❤ by GitHub

You can add multiple effects to a control. As you might have noticed this gives you a lot of freedom because unlike a custom renderer you specifically decide which control gets the effect without any need to subclass it. When creating an effect it is not mandatory to implement it in each platform. You can create an effect and choose to only implement it in iOS. It’s completely optional.

Creating our first Effect

We’re going to create an effect which puts an awesome cat as the background image of an Entry. To get started we create a class in our PCL that inherits from RoutingEffect which has no code but we’re going to use it to make sure we can consume our effect in our XAML code:

public class CatEffect : RoutingEffect
{
public CatEffect () : base (“SuperAwesome.CatEffect”)
{
}
}
view rawCatEffect.cs hosted with ❤ by GitHub

This class calls the RoutingEffect base class constructor and passes in a string parameter. Take note of this parameter as you will be seeing it later on in this sample. It is used to initialize an instance of this effect at runtime and is a concatenation of 2 variables we’ll be seeing in the platform-specific implementations of our effect.

Creating the platform-specific code

To actually create the custom Effect you need to subclass the PlatformEffect class in your platform-specific projects and each platform-specific PlatformEffect class subsequently exposes the following properties for you to use:

  • Container – the platform-specific control being used to implement the layout.
  • Control – the platform-specific control.
  • Element – the Xamarin.Forms control that’s being rendered.

When inheriting from PlatformEffect you also gain access to two methods for you to override: OnAttached and OnDetached. You can use OnAttached to apply your effect and OnDetached to clean up your effect. Now let’s create our effect shall we?

On iOS we implement it as follows:

using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using SampleApp.iOS.Effects;
[assembly: ResolutionGroupName(SuperAwesome)]
[assembly: ExportEffect(typeof(CatEffect), CatEffect)]
namespace SampleApp.iOS.Effects
{
public class CatEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
if (Control is UITextField)
{
// Set the border style to none to show background image.
(Control as UITextField).BorderStyle = UITextBorderStyle.None;
// Create an image and set it as background pattern.
var image = UIImage.FromBundle(cat.jpg).CreateResizableImage(new UIEdgeInsets(0, 10, 0, 10), UIImageResizingMode.Stretch);
Control.BackgroundColor = UIColor.FromPatternImage(image);
}
}
catch (Exception ex)
{
Console.WriteLine(Cannot set property on attached control. Error: , ex.Message);
}
}
protected override void OnDetached()
{
// Back to white.
Control.BackgroundColor = UIColor.White;
}
}
}
view rawCatEffectiOS.cs hosted with ❤ by GitHub

On Android our effect code looks like this:

using System;
using SampleApp.Droid.Effects;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ResolutionGroupName(SuperAwesome)]
[assembly: ExportEffect(typeof(CatEffect), CatEffect)]
namespace SampleApp.Droid.Effects
{
public class CatEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
if (Control is EntryEditText)
{
Control.SetBackgroundResource(Resource.Drawable.cat);
}
}
catch (Exception ex)
{
Console.WriteLine(Cannot set property on attached control. Error: , ex.Message);
}
}
protected override void OnDetached()
{
// Back to white.
Control.SetBackgroundColor(Android.Graphics.Color.White);
}
}
}
view rawCatEffectDroid.cs hosted with ❤ by GitHub

As you can see there are 2 assembly attributes decorating our effect.

[assembly:ResolutionGroupName (SuperAwesome)]
[assembly:ExportEffect (typeof(CatEffect), CatEffect)]
view rawCatEffect.cs hosted with ❤ by GitHub

You might remember I talked about passing a string value into the constructor of your RoutingEffect class in your PCL a bit higher up in this post. These two values uniquely identify this specific effect and are the linking pin between your PCL code and your platform-specific code. These two values need to match the string in your PCL code (concatenated with a period character in between). It’s what makes the whole thing come together!

The result of our Effects

Obviously this leaves a lot to be desired and it serves solely as a sample of how effects work and I can’t call this one production-worthy 🙂 There are however ways you can implement your effects that can be a lot more useful. Some samples include:

  • Creating drop shadows on visual elements
  • Setting keyboard types on an entry
  • Setting auto-correct settings on an entry
  • Etc.

 

Sharing is caring

Why did I create such a useless effect to show off how effects work instead of creating one from the list above? Because the ones I mentioned have already been created by other people! The beauty of Effects is that you can easily share them which is exactly what some people have done. The FormsCommunityToolkit is a project that tries to aggregate Effects (among other things) and you can contribute to it if you’ve created one. Since it already contains some nice ones you don’t have to recreate them yourself.

A word of warning…

You can attach effects to any type of view however you need to take care of the fact that someone might attach your effect to a Button even though it was meant to work with an Entry control. Xamarin Forms does nothing to stop this behaviour. You will need to take care of graceful exception handling yourself just in case this type of thing occurs either by also implementing it for Button or by silently (yet gracefully) failing.

This article was published on Microsoft and was quickly taken down. I thought you guys might like it.

At Connect(); in November, Microsoft is launching a preview of Visual Studio for Mac. This is an exciting development, evolving the mobile-centric Xamarin Studio IDE into a true mobile-first, cloud-first development tool for .NET and C#, and bringing the Visual Studio development experience to the Mac.

A New Member of the Visual Studio Family

At its heart, Visual Studio for Mac is a macOS counterpart of the Windows version of Visual Studio. If you enjoy the Visual Studio development experience, but need or want to use macOS, you should feel right at home. Its UX is inspired by Visual Studio, yet designed to look and feel like a native citizen of macOS. And like Visual Studio for Windows, it’s complemented by Visual Studio Code for times when you don’t need a full IDE, but want a lightweight yet rich standalone source editor.

Below the surface, Visual Studio for Mac also has a lot in common with its siblings in the Visual Studio family. Its IntelliSense and refactoring use the Roslyn Compiler Platform; its project system and build engine use MSBuild; and its source editor supports TextMate bundles. It uses the same debugger engines for Xamarin and .NET Core apps, and the same designers for Xamarin.iOS and Xamarin.Android.

Compatibility is a key focus of Visual Studio for Mac. Although it’s a new product and doesn’t support all of the Visual Studio project types, for those it does have in common it uses the same MSBuild solution and project format. If you have team members on macOS and Windows, or switch between the two OSes yourself, you can seamlessly share your projects across platforms. There’s no need for any conversion or migration.

Mobile-First, Cloud-First Development

The primary workloads supported by Visual Studio for Mac are native iOS, Android and Mac development via Xamarin, and server development via .NET Core with Azure integration. It gives you all the tools you need to develop the rich, native mobile app experiences that users expect today, and the cloud-based server back ends to power them.

It’s all powered by the C# language you know and love, with the latest C# 7 productivity enhancements. You get the performance of compiled code, the productivity of a modern type-safe language, access to the unique features of each platform, and a rich ecosystem of libraries and tools. You can use your existing experience across the mobile and cloud domains, sharing code between client and server. And with all your projects in one solution, you can take advantage of solution-wide cross-project refactoring and code navigation.

C# isn’t the only language supported in the Visual Studio for Mac preview. For the functional programmers among you, it includes excellent F# support, powered by the same F# compiler used in Visual Studio.

iOS, Android and Mac

With the fragmented mobile market today it’s important to be able to target a wide range of devices. Because it’s based on Xamarin Studio, Visual Studio for Mac has mature support for C#-based iOS, Android and Mac development with the Xamarin Platform. You can take advantage of your existing C# experience and libraries, and share common code across platforms, with full access to the native APIs so you can build a fast, polished native app experience.

For even greater code sharing, you can use the cross-platform Xamarin.Forms UI library, which provides a familiar XAML-based development environment that can target multiple platforms, including iOS, Android, macOS and the Universal Windows Platform (UWP)—though UWP development is currently only supported in Visual Studio—and maps to the native UI on each platform. When you need more control, you can mix and match Xamarin.Forms with direct access to the native toolkits. There’s a huge ecosystem of libraries available for Xamarin via NuGet, too, including platform-specific libraries, bindings to native code and portable .NET Standard libraries.

Like Visual Studio, Visual Studio for Mac has drag-and-drop designers for iOS and Android development that let you rapidly assemble and fine-tune your UI. For Xamarin.Forms, it has rich XAML IntelliSense and a side-by-side live preview, as Figure 1 shows. Both the designer and the live preview use a simulator to render your app exactly how it will appear on the device, and this even works for your custom controls.

The Xamarin.Forms XAML Live Preview
Figure 1 The Xamarin.Forms XAML Live Preview

Cutting-Edge Cloud

Almost every mobile app is backed by a service, and Visual Studio for Mac makes it easy to develop your app’s service with its support for the latest ASP.NET Core Web development platform. ASP.NET Core runs on .NET Core, the latest evolution of the .NET Framework and runtime. It’s been tuned for blazingly fast performance, factored for small install sizes, and reimagined to run on Linux and macOS, as well as Windows.

.NET Core gives you a huge degree of flexibility in how and where you develop and deploy your server application, whether in your own datacenter or on a cloud platform such as Microsoft Azure. Because both .NET Core and Xamarin Platform are open source, you won’t have to worry about vendor lock-in.

The Visual Studio for Mac support for .NET Core projects also allows you to write .NET Standard libraries, the new way to share code across .NET platforms going forward. .NET Standard libraries replace Portable Class Libraries (PCLs) and offer a much broader API surface area. Because .NET Core and Xamarin Platform are .NET Standard-compliant, they’re a great way to share code, both within your solution and via the NuGet Package Manager.

A Familiar Workspace

The Visual Studio for Mac workspace should be familiar to existing Visual Studio developers. When you first open it, you see a Welcome Page with a list of recently opened solutions, a feed of developer news and other information to help you get started.

To create a new solution, go to the File menu and select New Project, and you’ll see the workspace containing your new solution. As you can see in Figure 2, there’s a central tabbed source editor with a number of other docked windows or “pads” around it, such as Solution, Output, Properties, Document Outline and Toolbox. Like Visual Studio, this layout is highly customizable and switches automatically, depending on whether you’re coding, debugging or using the drag-and-drop designer.

The Visual Studio for Mac Workspace
Figure 2 The Visual Studio for Mac Workspace

The toolbar is familiar, too, but has a few notable differences:

On the left is the Run button, a dropdown to select the Active Configuration, as well as dropdowns to select the Run Configuration and Target Device. For cross-platform mobile development, it’s important to be able to easily switch the device or simulator on which you’re testing or debugging your app. The Run Configuration is like the startup project in Visual Studio, except that in addition to switching which project runs, you can also create custom-named sets of run options.

In the center of the toolbar is a notification area, which shows messages about various operations, such as building or restoring NuGet packages. When there’s a running operation, a cancel button shows up in the notification area. This is also where notifications about software updates are displayed. You can click on some notifications, such as build errors, and they’ll bring up a pad with more information.

At the right of the toolbar is the global search. In addition to helping you find things like commands and files in your solution, its camelCase filtering system makes it an excellent way to quickly activate commands, or jump to files or types in your solution. It can even kick off a Find in Files search in your solution, or open the NuGet Package Manager to search for a package.

The Solution pad works much the same as the Solution Explorer in Visual Studio, letting you explore and manage the structure of your solution, your project and the files in it. The context menu gives you a range of context-specific commands on the items in the solution tree, such as adding or removing files from projects, editing project references, opening Terminal windows in folders, and building or debugging specific projects.

The Errors pad shows any build warnings and errors, and is also where you can find the build log output in a split view. Unlike Visual Studio, there isn’t a single unified pad for all kinds of output. For example, an Application Output pad shows the output from your app when you run or debug it, and logs from NuGet operations are shown in a NuGet Console pad. The Properties pad contextually shows properties of whatever is currently focused and selected, and can be used to view and change the build action of files in the solution pad.

In the center is the heart of the IDE, the source editor, which has all the features you’d expect from a member of the Visual Studio family. Figure 3 shows C# IntelliSense and syntax highlighting in a .NET Core project. There’s also code folding, live underlining of errors and suggestions as you type, configurable automatic formatting, code navigation commands and an array of powerful refactoring tools.

IntelliSense in a .NET Core Project
Figure 3 IntelliSense in a .NET Core Project

Not all of the editor’s functionality is enabled by default. You can tweak the Visual Studio for Mac settings in the Preferences dialog, which is accessible from its Mac application menu. This is equivalent to the Options dialog in the Visual Studio Tools menu, and contains plenty of options to help you customize the IDE to work the way you want.

Unit testing is supported using NUnit, and other test runners can be plugged in via extensions. The tests discovered in your assembly are shown in a Unit Tests pad that can be accessed from the View | Pads menu. There’s also git version control integrated right into the source editor, with a row of tabs along the bottom of the editor to access the current file’s log, diff and blame view.

If you’d like to get up to speed quickly with some more tips and tricks, I encourage you to watch my “Become a Xamarin Studio Expert” session from Xamarin Evolve 2016 (xmn.io/xs-expert) as its content applies directly to Visual Studio for Mac.

Open Source Core

Like Xamarin Studio, Visual Studio for Mac is based on the open source MonoDevelop IDE, which is actively developed by Microsoft. It’s written entirely in C#, and has a rich extensibility model that you can use to add functionality ranging from simple editor commands to entirely new languages and project types. Even core features such as C# editing, Xamarin.iOS, Xamarin.Android and ASP.NET Core are implemented as extensions.

Like Visual Studio and Visual Studio Code, the C# support in Visual Studio for Mac is powered by the open source Roslyn Compiler Platform. You get the exact same IntelliSense experience you’re familiar with from Visual Studio, as well as support for in-editor live Analyzers and Code Fixes. Visual Studio for Mac even includes the Refactoring Essentials collection of Analyzers and Code Fixes by default.

Visual Studio for Mac supports editing a wide range of languages though the use of TextMate bundles, which provide syntax highlighting and simple IntelliSense. It includes a number of open source TextMate bundles from Visual Studio Code.

Creating an ASP.NET Core App

To show you how easy it is to get up to speed with Visual Studio for Mac, I’m going to walk though creating a simple ASP.NET Core back end. It’s for a hypothetical “Shared To-do List” mobile app, which allows multiple users to add items, and all users see the items that any of them post.

Please note that I’m writing this article using a pre-release version of Visual Studio for Mac, and some details of the UI may change in the release. However, the approaches and concepts discussed in this article will still apply.

After installing and opening Visual Studio for Mac, I start by clicking on the New Solution button on the welcome page, which opens the New Project dialog. I navigate into the Cloud section, choose the ASP.NET Core Web Application template, and click Next, then choose the Web API template. The Web API template creates a RESTful Web service which is perfect for a mobile back end, though you can add views to the project later to create a Web front end.

Finally, I name my project HelloVSMac and click Create. Visual Studio for Mac creates the projects using the dotnet templating engine, opens it and starts restoring the NuGet packages on which it depends. If you open the project file in the editor using the Tools | Edit File context menu on the project in the solution pad, you can see that it’s a minimalistic MSBuild-based project file that’s intended to be easy to understand. If you edit it directly and save it, the IDE will automatically reload your modified version.

Looking at the project in the solution pad, the key items are:

Packages: Your project’s NuGet package dependencies. ASP.NET Core, the .NET Core framework and the MSBuild targets that build the project are all installed via NuGet packages.

Program.cs: The entry point of your Web app. ASP.NET Core apps are programs, so there’s a Main method entry point that creates, builds and runs the WebHost at the heart of your app.

Startup.cs: Which defines a Startup class that was passed to the WebHost. This class contains your application’s initialization methods.

appsettings.json: Your app’s configuration settings. This is the ASP.NET Core equivalent of the ASP.NET web.config.

For the purposes of this walk-through, I’ll leave these all as is, and look at the ValuesController.cs file in the Views folder. This contains a ValuesController class registered on the [Route(“api/[controller]”)] route. The [controller] is a placeholder for the class name, so this is really the api/values route.

I’ll start by defining a very simple ToDoItem class and a ToDoList storage class. ToDoList is static so it can be shared among requests. In a real app you’d use a database for this, but it will do for now. I also rename the controller class to ToDoController (which makes the route api/todo), connect the Get and Post methods to the store, and clear out the other unused controller methods. The result can be seen in Figure 4.

Figure 4 The Controller and Its Simple Shared To-Do List Storage

This is now a complete, but very small, RESTful Web service. Let’s try it out.

I place a breakpoint in the Post method, and start debugging the app. The Output pad starts to show the output from the ASP.NET Core built-in kestrel Web server as the app starts up, by default on port 5000, but it won’t do anything else until it receives a request. You can open your Web browser and check 127.0.0.1:5000/api/todo, but it’ll just be an empty array.

Debugging a .NET Core Project
Figure 5  Debugging a .NET Core Project

Because there isn’t a mobile client for this service yet, it’s time to open the macOS Terminal app and use curl to send a POST request to the app:

This triggers the breakpoint in the debugger. You can inspect the value that has automatically been parsed from the JSON body of the request and converted into the ToDoItem object. You can see that Visual Studio for Mac automatically entered the debugging layout, and has all the debugger pads you’d expect: Stack, Locals, Threads, Breakpoints and so on.

Now, go back to the terminal and use curl to access the Get method, and you’ll see the JSON array containing the item that was added:

The next step is to build the mobile app, but I’ll let you explore that yourself. For more in-depth information on ASP.NET Core, I recommend checking out asp.net/get-started, and if you’d like to learn more about Xamarin development, there’s plenty of great material at developer.xamarin.com. Although there isn’t much documentation on Visual Studio for Mac yet, the Xamarin Studio documentation applies directly in most cases, and Visual Studio documentation is often applicable, too.

Wrapping Up

I hope this brief overview has whetted your appetite to try Visual Studio for Mac and make it your macOS IDE of choice for cloud and mobile development! If you have a Mac I encourage you to download the preview from VisualStudio.com, give it a spin, and let us know how you like it. We’re excited to hear your feedback to help guide it through the preview and beyond.

 

Source:

https://webcache.googleusercontent.com/search?q=cache:Vk2On-9psscJ:https://msdn.microsoft.com/en-us/magazine/mt790182.aspx+&cd=1&hl=en&ct=clnk&gl=uk

 

1. When you to open “android-ndk-r10c-darwin-x86_64.bin” with “Archive Utility.app” or other app.
2. Then you’ve got “android-ndk-r10c-darwin-x86_64.bin.cpgz”, OH! Crap it’s not extract but archive .bin to .cpgz extension.
Warning!! extracted file take more disk space up to 3.55 GB on disk
[Solution 1] recommended!!
1. open Terminal then type “chmod +x [path]/android-ndk-r10c-darwin-x86_64.bin” and press “Enter”, after that type only “[path]/android-ndk-r10c-darwin-x86_64.bin” and press “Enter” as below image.

After that Terminal was extract with 7-Zip SFX, as below detail.
7-Zip SFX 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18
p7zip Version 9.20 (locale=utf8,Utf16=on,HugeFiles=on,4 CPUs)
Processing archive: /Users/dtkad/Downloads/android-ndk-r10c-darwin-x86_64.bin
2. just wait process until Terminal show “Everything is Ok”

[Solution 2]

1. It’s too easy just rename by remove “.bin” if your non-extension file can be execute.
“android-ndk-r10c-darwin-x86_64.bin”
to
“android-ndk-r10c-darwin-x86_64”
you should see it’s as execute file, check it by right-click and choose “Get Info”, you will see detail like below image.
2. double click on “android-ndk-r10c-darwin-x86_64” execute file or open with “Archive Utility.app”,  so if you not see “Archive Utility.app” in both Launchpad and Application folder, it should be here “/System/Library/CoreServices” like below image.
then the Terminal was run and execute file will do extract process, leave it run until it’s show message as below.

 

Everything is Ok
logout
[Process completed]
 
3. Let’s see your extracted folder “android-ndk-r10c”, it’s contain in “Users” by default, for example my users is “poraweeraksasin” from step 2. name on bar, see below image.

All credits to the original author for doing this. Although I’m trying to extend it in the coming days, but props to Adam for finding this one out!

Go to https://www.syntaxismyui.com/xamarin-forms-in-anger-cards/ and follow his other tutorial as well.

 

The #1 request I get for the Xamarin.Forms in Anger is for a Google or Facebook like card view. Today is the day that I fulfill those requests.

To be completely honest, I’ve been thinking about how to do a card view for a while and let me tell you, it’s not easy. Especially when you try to stick with the “in the box” components of Xamarin.Forms. My first attempt at it was hideous.

Hideous Forms

Hideous would be the most polite way of saying it was crap. I started off using BoxViews to draw the lines and contain the whole thing in a Xamarin.Forms Grid. Ouch, yes hideous.

The Grid was becoming a nightmare with all the extra rows and columns needed for lines. What I wouldn’t do for some HTML Tables with a borders = 1 in Xamarin.Forms. I thought of putting in a feature request to the team, but didn’t. I don’t want them to laugh at me. 😉

Waffle Fries to the Rescue

With the BoxViews not working out, I went to lunch to clear my head and to think. I love lunch and I don’t miss a meal. That day, I decided to go to Chick Fil A and get a chicken sandwich with a side of epiphany fries.

There I was, eating my chicken and dunking my fries in ketchup (Sauce de American). When I dipped a waffle fry into the ketchup, the ketchup squeezed through the holes and made a red checkerboard on top of the fry. Then it hit me. Bam!

I was going about the card UI backwards or forwards. Either way, it was the wrong way. I had to do an about face and approach it in another way. The way the ketchup came up through the fry not by putting ketchup onto the fry.

A Grid of Lines

As soon as I got home, I worked up a Xamarin.Forms Grid with some padding, row and column spacing. In addition to those settings, I also set the background color of the grid to a medium dark grey. Then added ContentViews with white backgrounds into each cell of the Grid. This is what it looked like when I finished.

GridLines

The white panels acted like the ketchup on my waffle fries and the borders are the potato. Yes, I know, it’s strange to describe Xamarin.Forms design techniques using food, but stay with me; it gets better. Now that I knew the technique worked and was a heck of a lot less messy, I pushed on.

Content View Panels

Each CardView is made up of 5 ContentViews with a background color set to the designed color. Here are some of the background colors for each panel.

Panels

The CardView.cs file would have been gigantic if I kept all the code in the same file so I broke it up into different ContentViews. Here are the names for each ContentView that makes up the CardView.

CardViews

The CardDetailsView has a column span of three to horizontally bridge the two IconLableViews and the ConfigIconView. The CardStatusView has a row span of two to complete the vertical lefthand status bar.

The CardView Code

For the demo, I put a couple of CardViews in a vertical StackLayout. If I had a lot of cards, I would prefer to use a ListView. Hopefully a reader will let me know how well this design works in a ListView. It should be ok, especially while using the Grid and not a bunch of nested StackLayouts. I’ve learned my lesson.

public class CardView : ContentView
{
public CardView (Card card)
{
Grid grid = new Grid {
Padding = new Thickness (0, 1, 1, 1),
RowSpacing = 1,
ColumnSpacing = 1, 
BackgroundColor = StyleKit.CardBorderColor,
VerticalOptions = LayoutOptions.FillAndExpand,
RowDefinitions = {
new RowDefinition { Height = new GridLength (70, GridUnitType.Absolute) },
new RowDefinition { Height = new GridLength (30, GridUnitType.Absolute) }
},
ColumnDefinitions = {
new ColumnDefinition { Width = new GridLength (4, GridUnitType.Absolute) },
new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength (100, GridUnitType.Absolute) },
new ColumnDefinition { Width = new GridLength (50, GridUnitType.Absolute) }
}
};

grid.Children.Add (
new CardStatusView (card)
, 0, 1, 0, 2);

grid.Children.Add (new CardDetailsView (card), 1, 4, 0, 1);

grid.Children.Add (
new IconLabelView (
card.StatusMessageFileSource,
card.StatusMessage
)
, 1, 1);

grid.Children.Add (
new IconLabelView (
card.ActionMessageFileSource,
card.ActionMessage
)
, 2, 1);

grid.Children.Add (new ConfigIconView (), 3, 1);

Content = grid;
}
}

With all the refactoring; the CardView looks small and plain but the devil is in the ContentViews.

 

Final Layout:

Solution

The code for this sample is up on GitHub in the “In Anger” repository. For this post, I broke the code out into a separate directory and solution to make it easier for you to reuse the CardView without getting confused with all the other code and resources from other posts.

Moar Epiphany Fires

Who knew that a humble waffle fry would be the answer to the Xamarin.Forms CardView? Not me; I go for the chicken. Don’t you worry dear read, I will continue to go to “Chick Fil a” to get more Xamarin.Forms design inspiration in the future. Stay tuned to this blog and, if you have a design challenge, just put it in the comments below or email me at adam [at] adamjwolf dot com.

Xamarin.Forms in Anger Series

Can Xamarin.Forms produce good looking cross-platform UI from a single codebase? Each “In Anger” blog post will tackle a single page of a beautifully designed iOS or Android application. My job will be to reproduce the design in Xamarin.Forms as faithfully as possible.