For a while now I have been having trouble with the Binding context in Xamarin.
Here's my Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gren
{
public class TaskModel
{
public string Title { get; set; }
public int Duration { get; set; }
}
}
Here's my ViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gren.ViewModel
{
public class HomeViewModel
{
public TaskModel TaskModel { get; set; }
public HomeViewModel()
{
TaskModel = new TaskModel
{
Title = "Creating UI",
Duration = 2
};
}
}
}
And here's my view's code behind, where I bind my ViewModel to the View:
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Gren.ViewModel;
namespace Gren
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ModelBinding : ContentPage
{
public ModelBinding()
{
InitializeComponent();
BindingContext = new HomeViewModel();
}
}
}
My View's code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Gren.ModelBinding"
BackgroundColor="Red">
<ContentPage.Content>
<StackLayout>
<Label Text="Title ofTask"/>
<Entry Text="{Binding {}TaskModel.Title}"/>
<Label Text="Duration ofTask"/>
<Entry Text="{Binding {}TaskModel.Duration}"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
This runs well.
Now I'm sure you'd notice the {} in the binding tag of the text property of each entry. Yeah, it is normally not supposed to be there but when I run it without the {}, it won't display the values of the binded property as it would with the {} in front.
I want to know if there's a better way to code this.
Text="{Binding Path=TaskModel.Title}"? - slugster