Xamarin中的MVVM绑定

时间:2017-10-17 13:58:21

标签: c# xamarin mvvm xamarin-binding

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

1 个答案:

答案 0 :(得分:0)

嗯真的很奇怪.. 这真的是你XAML的全部视图吗?因为我怀疑那里的其他东西可能会造成这种情况。

我希望您尝试在XAML中完成此操作。

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