Xamarin.Forms Projects
上QQ阅读APP看书,第一时间看更新

Using the ValueConverter

We want to use our brand new StatusColorConverter in the MainView. Unfortunately, we have to jump through some hoops to make this happen. We need to do three things:

  • Define a namespace in XAML
  • Define a local resource that represents an instance of the converter
  • Declare in the binding that we want to use that converter

Let's start with the namespace:

  1. Open Views/MainView.xaml.
  2. Add the following namespace to the page:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:DoToo.Converters"
x:Class="DoToo.Views.MainView"
Title="Do Too!>

Add a Resource node to the MainView.xaml file:

  1. Open Views/MainView.Xaml.
  2. Add the following ResourceDictionary, shown in bold under the root element of the XAML file:
<ContentPage ...>
<ContentPage.Resources>
<ResourceDictionary>
<converters:StatusColorConverter
x:Key="statusColorConverter" />

</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.ToolBarItems>
<ToolbarItem Text="Add" Command="{Binding AddItem}" />
</ContentPage.ToolbarItems>
<Grid ...>
</Grid>
</ContentPage>

This has the same form as the global resource dictionary, but since this one is defined in the MainView, it will only be accessible from there. We could have defined this in the global resource dictionary, but it's usually best to define objects that you only consume in one place as close to that place as possible.

The last step is to add the converter:

  1. Locate the BoxView node in the XAML.
  2. Add the BackgroundColor XAML, which is marked in bold:
<BoxView Grid.RowSpan="2" 
BackgroundColor="{Binding Item.Completed,
Converter={StaticResource
statusColorConverter}}"
/>

What we have done here is bound a Boolean value to a property that takes a Color object. Right before the data binding takes place, however, the ValueConverter converts the Boolean value to a color. This is just one of the many cases where a ValueConverter comes in handy. Keep this in mind when you are defining the GUI.