如何在 CollectionView 项目中添加图库中的照片?

How to add Photo from Gallery in CollectionView Project?

我有一个 collection 视图,我想将图库中的照片添加到 it.If 我在标签中添加例如来自图库的图片 Image.it works.But 我想在我的 collection 视图中添加它,但我不明白为什么它不添加图片

XAML

<StackLayout>
        <Button Text="Select"
                     Clicked="Handle_Clicked" />
       
        <StackLayout HeightRequest="120" BackgroundColor="LightGray">
            <!--  <Label Text="No photo yet" TextColor="#616161" HorizontalOptions="CenterAndExpand" FontSize="Large"
                                VerticalOptions="CenterAndExpand"    ></Label>-->
            <CollectionView  x:Name="AddCar" ItemsSource="{Binding Types}"      
                  SelectionMode="None">
                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Horizontal"
                />
                </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Grid >
                            <Grid.RowDefinitions>
                                <RowDefinition Height="120" />
                            </Grid.RowDefinitions>
                            <Frame CornerRadius="10" BorderColor="Black" Margin="5,5,5,5" Padding="0" >
                                <Image Source="{Binding Source}"
                          HorizontalOptions="Center" 
                         BackgroundColor="{Binding CustButtonColor}"/>
                            </Frame>
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>

        </StackLayout>
    </StackLayout>

代码隐藏

 public MainPage()
        {
            InitializeComponent();
            BindingContext = new VM();
        }

        async void Handle_Clicked(object sender, System.EventArgs e)
        {
            //! added using Plugin.Media;
            await CrossMedia.Current.Initialize();
            var image = new Image();
            //// if you want to take a picture use this
            // if(!CrossMedia.Current.IsTakePhotoSupported || !CrossMedia.Current.IsCameraAvailable)
            /// if you want to select from the gallery use this
            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                await DisplayAlert("Not supported", "Your device does not currently support this functionality", "Ok");
                return;
            }

            //! added using Plugin.Media.Abstractions;
            // if you want to take a picture use StoreCameraMediaOptions instead of PickMediaOptions
            var mediaOptions = new PickMediaOptions()
            {
                PhotoSize = PhotoSize.Medium
            };
            // if you want to take a picture use TakePhotoAsync instead of PickPhotoAsync
            var selectedImageFile = await CrossMedia.Current.PickPhotoAsync(mediaOptions);

          /*  if (selectedImage == null)
            {
                await DisplayAlert("Error", "Could not get the image, please try again.", "Ok");
                return;
            }
          */
            image.Source = ImageSource.FromStream(() => selectedImageFile.GetStream());
            var page = new VM();
            page.Types.Add(image);
        }
    }

虚拟机

 class VM : INotifyPropertyChanged
    {
        //  public Command Photo { get; set; }
        public ObservableCollection<Image> types { get; set; }
        public ObservableCollection<Image> Types { get => types; set { types = value; OnPropertyChanged("Types"); } }
        public VM()
        {
            //  Photo = new Command(OnPickPhotoButtonClicked);
            Types = new ObservableCollection<Image>();
            Types.Add(new Image() { Source = "heart", BackgroundColor = Color.White });
            Types.Add(new Image() { Source = "heart", BackgroundColor = Color.White });
            Types.Add(new Image() { Source = "heart", BackgroundColor = Color.White });
            Types.Add(new Image() { Source = "heart", BackgroundColor = Color.White });
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

请帮忙。 link 我的项目 GitHub

https://github.com/kamenskyh/PhotoFromGallery/tree/master/Photos

首先,保留对您的 VM 的引用

    VM ViewModel;

    public MainPage()
    {
        InitializeComponent();
        BindingContext = ViewModel = new VM();
    }

然后,添加图片时,不要创建新的 VM 实例

var page = new VM();
page.Types.Add(image);

改为使用您的页面已绑定到的 VM 实例

ViewModel.Types.Add(image);