2

I want to use compiled bindings in my Xamarin Forms app in combination with Prism.

I created a small xamarin forms app with a simple view, viewmodel and prism (prism:ViewModelLocator.AutowireViewModel="True"). Classic binding works as expected. How should I implemented compiled binding without creating the binding context twice?

Classic binding with prism: HomePage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="CompiledBinding.Views.HomePage">
    <StackLayout>
        <!-- Place new controls here -->
        <Label Text="{Binding Name}" 
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    </StackLayout>  
</ContentPage>

HomePageViewModel.cs:

using Prism.Mvvm;
using Prism.Navigation;
using System;
using Xamarin.Forms;

namespace CompiledBinding.ViewModels
{
    public class HomePageViewModel : BindableBase
    {
        string _name = "Compiled binding test";

        public HomePageViewModel(INavigationService navigationService)
        {
            var nav = navigationService;

            Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            {
                // Do something
                Name = DateTime.Now.ToString("yyyy MMMM dd hh:mm:ss");

                return true; // True = Repeat again, False = Stop the timer
            });
        }

        public string Name
        {
            get { return _name; }
            set { SetProperty(ref _name, value); }
        }
    }
}

Adding the binding context to the xaml page again, is not an option:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             xmlns:viewModels="clr-namespace:CompiledBinding.ViewModels"
             x:Class="CompiledBinding.Views.HomePage"
             x:DataType="viewModels:HomePageViewModel">
    <ContentPage.BindingContext>
        <viewModels:HomePageViewModel />
    </ContentPage.BindingContext>
    <StackLayout>
        <!-- Place new controls here -->
        <Label Text="{Binding Name}" 
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    </StackLayout>  
</ContentPage>

Besides of defining the binding context again, it also results in the error: no public parameterless constructor.

Do I oversee something? Does anyone know how to work with compiled bindings together with prism?

Luc Baeten
  • 21
  • 2

0 Answers0