一段时间以来,我一直在使用 Xamarin 中的绑定上下文遇到问题。
这是我的模型:
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; }
}
}
这是我的视图模型:
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
};
}
}
}
这是我的视图代码,我将我的 ViewModel 绑定到视图:
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();
}
}
}
我的视图的代码:
<?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>
这运行良好。现在我确定您会注意到{}
每个条目的 text 属性的绑定标记中的 。是的,它通常不应该在那里,但是当我在没有 的情况下运行它时{}
,它不会像{}
前面的那样显示绑定属性的值。我想知道是否有更好的编码方式。