【问题标题】:MVVM Binding in XamarinXamarin 中的 MVVM 绑定
【发布时间】: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


【解决方案1】:

嗯,这真的很奇怪.. 这真的是您对 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}"/>

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2021-10-16
    • 2018-08-14
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2021-04-28
    • 2018-07-14
    相关资源
    最近更新 更多