存取巢状XAML项目

nue99wik  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(99)

**下午好!**情况是,collectionView中还有另一个collectionView。我通过一个属性从代码中获得第一个collectionView的方法和属性

x:Name="cv1"

但是代码无法访问第二个集合。错误是The name "cv2" does not exist in the current context. My XAML:

<CollectionView x:Name="cv1">
   <CollectionView.ItemTemplate>
      <DataTemplate>
         <Frame Margin="5">
            <Frame.GestureRecognizers>
               <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
            </Frame.GestureRecognizers>
            <StackLayout>
               <Label Text="{Binding Key}"/>
               <CollectionView x:Name="cv2">
                  <CollectionView.ItemTemplate>
                     <DataTemplate>
                        <StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
                           <Label Text="{Binding DateCase}" HorizontalOptions="Start"/>
                           <Label Text="{Binding NumCase}" HorizontalOptions="CenterAndExpand"/>
                           <Label Text="{Binding Serial}" HorizontalOptions="CenterAndExpand"/>
                           <Label Text="{Binding Time}" HorizontalOptions="End"/>
                        </StackLayout>
                     </DataTemplate>
                  </CollectionView.ItemTemplate>
               </CollectionView>
            </StackLayout>
         </Frame>
      </DataTemplate>
   </CollectionView.ItemTemplate>
</CollectionView>

下面是代码:

cv1.ItemsSource = Cases; //There is access to the collection
cv2.ItemsSource = TimeLine; //There is no access to the collection
cv2.IsVisible = flag;

告诉我怎么了?该怎么挖?谢谢。
预期:通过单击包含Collectionview的Frame,isVisible属性更改了其值。
Turn out:无法访问Frame内部的collectionView,而Frame又不在collectionView内部。

mctunoxg

mctunoxg1#

当然,你不能从代码中访问cv2。名称CV2是数据模板的一部分,而不是你的页面。
你实际上要问的是:如何在DataTemplate中进行访问控制。
每次插入CV1项时,都会生成新的CV2。您需要在当前项的上下文中搜索它。(如果需要使用此方法)
你实际上要做的是:
1.使用绑定。
1.为数据模板(CV1项)设置x:DataType。
1.将CV2 ItemSource绑定到集合x:DataType模型的列表。
(编辑)操作示例:
假设您有Model,您想将它用于CollectionView中的每个项目。

<DataTemplate x:DataType="model:MyModel">

这个“model:“是一个命名空间。您可以在内容页面中设置它。

xmlns:model="clr-namespace:MyNameSpace"

之后,如果您的DataTemplate中有图像,则可以执行以下操作:

<Image Source="{Binding Image}"\>

其中Image是MyModel类的属性。VisualElement(在本例中为Image)将从模型的属性中获取其属性。
您所要做的就是将MyModel类型的ObservableCollection绑定到CollectionView的ItemSource。

<CollectionView ItemsSource="{Binding MyModels}">

在ViewModel中,您有:

[ObservableProperty]
 ObservableCollection<MyModel> _myModels= new();

离题:你最终需要的是RangeObservableCollection。在这里你可以静默地添加项目列表,并通知你完成了添加项目,这样你就不用为每个项目触发OnChange。否则,当你添加太多项目时,你的CollectionView的性能会受到影响。
我喜欢手动编写类并继承ObservableCollection,但是在其他库中也有这样的类可以使用。

相关问题