Xamarin将基本BindingContext形成为ViewModel

时间:2019-09-19 14:32:15

标签: xamarin xamarin.forms

我正在尝试从XAML视图到Xamarin Forms(4.2)应用程序中的视图模型进行一些基本数据绑定。我从另一个页面导航到PhotoUploadPage

PhotoUploadPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="AgentConnectMobile.Views.PhotoUploadPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="Upload Photo"
    mc:Ignorable="d">

    <ContentPage.Content>
            <!--Upload.Id below isn't showing -->
            <Label Text="{Binding Upload.Id}" />
    </ContentPage.Content>

</ContentPage>

PhotoUploadPage.xaml.cs

public partial class PhotoUploadPage : ContentPage
{
    PhotoUploadViewModel viewModel;

    public PhotoUploadPage(PhotoUploadViewModel viewModel)
    {
        this.viewModel = viewModel;
        BindingContext = this.viewModel;

        InitializeComponent();
    }
}

PhotoUploadViewModel.cs

public class PhotoUploadViewModel : BaseViewModel
{
    public Upload Upload { get; set; }

    public PhotoUploadViewModel(Upload upload = null)
    {
        Upload = upload;
    }
}

Upload.cs

public class Upload
{
    public string Id;
}

导航到PhotoUploadPage

var upload = new Upload
{
    Id = "abc123",
};

await Navigation.PushAsync(new PhotoUploadPage(new PhotoUploadViewModel(upload)));

我在PhotoUploadPage.xaml.cs中设置了断点,并且设置了BindingContext,并且可以在其上看到带有我的ID值的Upload,但该值从未出现在Label文本中。我还切换了InitializeComponent()的顺序并设置了BindingContext,但这也不能解决任何问题。

我在做什么错?我相信我正在其他地方这样做,并且效果很好...

0 个答案:

没有答案
相关问题