有一段时间我在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绑定到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();
}
}
}
我的观点代码:
<?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属性的绑定标记中的{}
。是的,它通常不应该存在但是当我在没有{}
的情况下运行时,它不会像前面的{}
一样显示绑定属性的值。
我想知道是否有更好的方法来编码。
答案 0 :(得分:0)
我希望您尝试在XAML中完成此操作。
xmlns:viewModels="clr-namespace:Gren.ViewModels;assembly=Gren"
<ContentPage.BindingContext>
<viewModels:HomeViewModel/>
</ContentPage.BindingContext>
<Entry Text="{Binding TaskModel.Title}"/>