【问题标题】:Accessing object's property from View从视图访问对象的属性
【发布时间】:2019-08-14 02:42:08
【问题描述】:

我在 Models 文件夹中有一个 Booking 类。我在导航到类时已经传递了 Booking 实例,现在如何从视图中访问 Booking 的属性?

我的视图模型:

public class BookingEditViewModel : ViewModelBase
{
    public Booking Booking { get;set; }

    public override void OnNavigatedTo(INavigationParameters parameters)
    {
        Booking = parameters.GetValue<Booking>("booking");
    }
}

我的观点:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
            xmlns:booking="clr-namespace:HelloWorldPrism.Models"
            prism:ViewModelLocator.AutowireViewModel="True"
            x:Class="HelloWorldPrism.Views.BookingEdit">

    <StackLayout>
        <Label Text="{Binding Booking.Id}"/>
        <Label Text="{Binding Booking.CustomerId}"/>
    </StackLayout>
</ContentPage>

我的模特:

public class Booking
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
}

我已将 Models 命名空间添加为 xmlns 的一部分,接下来我该怎么做才能访问 Booking 的属性?

编辑: 如果我只是在类的构造函数中向 Booking 属性添加任何值,Label 将打印出这些值。

    public BookingEditViewModel(BookingService bookingService, INavigationService navigationService) : base(navigationService)
    {
        this.bookingService = bookingService;
        Booking = new Booking { Id = 999, CustomerId = 2222, };
    }

所以问题似乎是当在 OnNavigatedTo 中更新 Booking 时,更新不会传播回 UI。我已将 BindingMode 更改为 TwoWay,但仍然无法正常工作。我该如何解决?

【问题讨论】:

  • 您的代码对我来说看起来不错 - 到底是怎么回事?是否有任何运行时错误或调试输出消息?
  • 你在哪里设置DataContextBindingContext? Prism 会为您这样做吗?
  • 视图的标签没有显示任何内容。如果我没记错的话,BindingContext 是由 Prism 设置的
  • 你的BookingViewModel在哪里?永远不要绑定到模型(除非这是一个玩具项目)......
  • @Haukinger 我确实将 View 绑定到 ViewModel。查看我的虚拟机有一个名为 Booking 的属性

标签: xaml xamarin.forms prism


【解决方案1】:

好的,找到答案了。基本上我的问题与这个问题相同:Prism Xamarin Forms View is not updated after changing the model in OnNavigatedTo

我只需要把属性改成这样:

    public Booking Booking
    {
        get => booking;
        set => SetProperty(ref booking, value);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    相关资源
    最近更新 更多