【发布时间】:2018-03-29 06:06:17
【问题描述】:
一段时间以来,我一直在 Xamarin 中的 Binding 上下文中遇到问题。
这是我的模型:
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; }
}
}
这是我的 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
};
}
}
}
下面是我的视图代码,我将我的 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 属性的绑定标记中的 {}。是的,它通常不应该存在,但是当我在没有{} 的情况下运行它时,它不会像前面的{} 那样显示绑定属性的值。
我想知道是否有更好的编码方式。
【问题讨论】:
-
我的 Xamarin 几乎不存在而且相当生锈......但你试过
Text="{Binding Path=TaskModel.Title}"吗?
标签: c# xamarin mvvm xamarin-binding