1

一段时间以来,我一直在使用 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 属性的绑定标记中的 。是的,它通常不应该在那里,但是当我在没有 的情况下运行它时{},它不会像{}前面的那样显示绑定属性的值。我想知道是否有更好的编码方式。

4

1 回答 1

0

嗯,这真的很奇怪.. 这真的是您对 XAML 的全部看法吗?因为我怀疑那里的其他东西可能会导致这种情况。

我希望看到您尝试并完全在 XAML 中进行设置。

  1. 现在在您的视图代码中注释掉您在 C# 中的 BindingContext。
  2. 在视图 XAML 中,为您的视图模型添加一个命名空间引用(不知道您的确切设置,假设您的虚拟机位于名为 ViewModels 的文件夹中),它将是这样的:
 xmlns:viewModels="clr-namespace:Gren.ViewModels;assembly=Gren"
  1. 然后在 XAML 中为整个页面设置绑定上下文。
<ContentPage.BindingContext>
    <viewModels:HomeViewModel/>
</ContentPage.BindingContext>
  1. 现在,使用正常的绑定语法,它应该没问题(除非如前所述,您的视图 XAML 中存在其他东西会破坏这一点)。
<Entry Text="{Binding TaskModel.Title}"/>
于 2018-04-18T16:33:41.917 回答