如何以Xamarin形式在XAML文件中使用C#类

时间:2019-04-30 20:00:20

标签: c# xaml xamarin xamarin.forms

我有以下C#类:

public class Appointment
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime Date { get; set; }
        public string Status { get; set; }
    }

在alistview中轻按以下内容时,我传递此类的对象:

private async void ListAppointments_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            if (e.Item is Appointment appointment)
            {
                await Navigation.PushAsync(new CheckAppointmentDetails(appointment));
            }
        }

还有我的CheckAppointmentDetails类的代码:

public partial class CheckAppointmentDetails : ContentPage
    {
        private readonly Appointment appointment;
        public CheckAppointmentDetails (Appointment appointment)
        {
            InitializeComponent ();
            this.appointment = appointment;
        }
    }

现在,我想知道如何在CheckAppointmentDetails XAML文件中使用约会对象的属性,以便可以在标签中显示这些属性,例如:

<StackLayout>
        <Label Text="{Binding Source=appointment, Path=Name}"/>
</StackLayout>

1 个答案:

答案 0 :(得分:4)

首先,您只能将数据绑定到公共属性。您还需要为页面设置BindingContext

public partial class CheckAppointmentDetails : ContentPage
{
    public Appointment appointment { get; set; }

    public CheckAppointmentDetails (Appointment appointment)
    {
        InitializeComponent ();

        BindingContext = this.appointment = appointment;
    }
}

然后在XAML中

<StackLayout>
    <Label Text="{Binding appointment.Name}"/>
</StackLayout>