如何将属性绑定到 CollectionView DataTemplate 中的元素

问题描述

我正在尝试将 IsVisible 属性绑定到 StackLayout 内的 DataTemplate,但我无法使其工作。

我已经尝试过 this post,但在 x:Reference 中它不允许我将 x:NameCollectionView 放入。

<CollectionView x:Name="myCollectionView"
            HorizontalOptions="FillAndExpand"
            ItemsSource="{Binding myBookList}">

  <CollectionView.ItemTemplate>
      <DataTemplate x:Name="dataTemplate">
          <ContentView>
              <StackLayout HorizontalOptions="EndAndExpand"
                           IsVisible="{Binding StackIsVisible}"
                           Orientation="Horizontal">
                  <Grid>
                      <ImageButton Margin="0,25,0"
                                   HorizontalOptions="EndAndExpand"
                                   Source="img1"
                                   WidthRequest="25" />
                      <ImageButton Source="img2"
                                   WidthRequest="25"
                                   HorizontalOptions="End" />
                  </Grid>
                  <ImageButton x:Name="myImageButton"
                               HorizontalOptions="EndAndExpand"
                               Source="img3"
                               WidthRequest="25" />
              </StackLayout>
          </ContentView>
      </DataTemplate>
   </CollectionView.ItemTemplate>

viewmodel 和视图正确连接,因为我有其他绑定工作,但这个对我不起作用。

     private bool _StackIsVisible;
     public bool StackIsVisible
     {
             get => _StackIsVisible;
             set
             {
                 _StackIsVisible = value;
                 OnPropertyChanged();
             }
     }
     public viewmodel(){
           StackIsVisible=false;
     }

解决方法

使用 Reference 时不必指定“名称”关键字

<StackLayout IsVisible="{Binding Source={x:Reference myCollectionView},Path=BindingContext.StackIsVisible}" ...>