We want to use our brand new StatusColorConverter object in 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 the converter
Let's start with the namespace:
- Open Views/MainView.xaml.
- 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:
- Open Views/MainView.xaml.
- Add the following ResourceDictionary element, 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 MainView, it can only be accessed from there. We could have defined this in the global resource dictionary, but it's usually more efficient 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:
- Locate the BoxView node in the XAML file.
- 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 bind a Boolean value to a property that takes a Color object. Right before the data binding takes place, however, ValueConverter converts the Boolean value into a color. This is just one of the many cases where ValueConverter comes in handy. Keep this in mind when you define the GUI.