一段时间
以来,我一直在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
};
}
}
}
这是我的视图代码隐藏,我将视图模型绑定到视图:
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 属性的绑定标记中的{}
。是的,它通常不应该在那里,但是当我在没有{}
的情况下运行它时,它不会像前面的{}
那样显示绑定属性的值。我想知道是否有更好的方法来编写代码。
嗯,
这真的很奇怪。这真的是你对 XAML 的全部看法吗?因为我怀疑那里可能有其他东西导致了这种情况。
我希望看到您尝试完全在 XAML 中执行此操作。
- 现在,在视图的代码隐藏中注释掉 C# 中的 BindingContext。
- 在视图 XAML 中,添加对视图模型的命名空间引用(不知道确切设置,假设 VM 位于名为 ViewModel 的文件夹中),它将如下所示:
xmlns:viewModels="clr-namespace:Gren.ViewModels;assembly=Gren"
- 然后在 XAML 中为整个页面设置绑定上下文。
<ContentPage.BindingContext>
<viewModels:HomeViewModel/>
</ContentPage.BindingContext>
- 现在,使用正常的绑定语法,它应该没问题(除非如前所述,XAML 视图中存在其他破坏这一点的东西)。
<Entry Text="{Binding TaskModel.Title}"/>