传输数据绑定设置Xamarin

时间:2019-07-06 19:49:21

标签: c# xamarin.forms data-binding

我有一个Class Objects的CollectionView和一个检索SelectedItem并打开ClassInfoPage的按钮。我想知道是否有一种方法可以将与SelectedItem相同的bindingcontext应用于ClassInfoPage。我的目标是让ClassInfoPage使用与SelectedItem相同的Class对象,而不必从SelectedItem检索对象,在ClassInfoPage中对其进行修改,然后将其放回其ObservableCollection中。预先感谢

CollectionView xaml

<CollectionView ItemsSource="{Binding Classes}" x:Name="ClassesCollectionView" SelectionMode="Single" HeightRequest="0">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <FlexLayout Direction="Row" AlignItems="Center" JustifyContent="SpaceEvenly" HeightRequest="35">
                            <Label Text="{Binding ClassName}" FontSize="Micro" />
                            <Label Text="{Binding ClassStatus}" FontSize="Micro"/>
                            <DatePicker Date="{Binding ClassStartDate}" FontSize="Micro"/>
                            <DatePicker Date="{Binding ClassEndDate}" FontSize="Micro"/>
                        </FlexLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>

到目前为止,我在ClassInfoButton click事件中的代码

private async void ClassInfoButton_OnClicked(object sender, EventArgs e)
        {

            FlexLayout selectedClass = ClassesCollectionView.SelectedItem as FlexLayout;
            await Navigation.PushAsync(new ClassInfoPage());
        }

ClassInfoPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TermManager.ClassInfoPage">
    <ContentPage.Content>
        <StackLayout>
            <FlexLayout AlignItems="Center" Direction="Row" JustifyContent="SpaceBetween">
            <DatePicker Date="{Binding ClassStartDate}"/>
            <Editor Text="{Binding ClassName}"/>
            <DatePicker Date="{Binding ClassEndDate}"/>
        </FlexLayout>
            <Editor Text="{Binding ClassNotes}"/>
            <Editor Text="{Binding ClassTeacherName}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

1 个答案:

答案 0 :(得分:0)

您需要将SelectedItem投射为MyClass(无论是什么)而不是FlexLayout,然后将其传递给ClassInfoPage

private async void ClassInfoButton_OnClicked(object sender, EventArgs e)
{
    MyClass selectedClass = ClassesCollectionView.SelectedItem as MyClass;
    await Navigation.PushAsync(new ClassInfoPage(selectedClass));
}

然后在ClassInfoPage

public ClassInfoPage(MyClass data) 
{
  this.BindingContext = data;
}

C#对象是通过引用传递的,因此您对ClassInfoPage中的对象所做的任何更改都应反映在首页上,尽管您可能需要刷新UI(或使用INotifyPropertyChanged)来看到