如何将命令从 ViewModel 绑定到位于自己文件中的 DataTemplate

我正在使用带有 ItemTemplateSelector 的可绑定堆栈布局。我的数据模板位于另一个文件中,该文件是作为 MergedResourceDictionay 包含在 MainView 中的 ResourceDictionary。在我的一个 DataTemplates 中,我有带有 TapGestureRecognizer 的标签,它应该在 MainViewViewModel 中触发命令,但我似乎无法开始工作......


我尝试Source={x:Reference MainPage}在我的命令绑定中使用它,但无法引用它,因为它不在同一个文件中


(Xamarin.Forms.Xaml.XamlParseException:“位置 28:51。找不到 MainPage 引用的对象”)


<--! this is snippet from MainPage  -->

 <ScrollView Orientation="Vertical" Grid.Row="1">

            <local:BindableStackLayout BindableLayout.ItemsSource="{Binding Day.TodayEntry}"

                     x:Name="BindableStack" Spacing="10" Margin="10" 

                           BindableLayout.ItemTemplateSelector="{StaticResource CardDetailTemplateSelector}"/>

        </ScrollView>


<--! this is problematic snippet from data template  -->


<Label Text="REMOVE" FontSize="Medium" TextColor="White" HorizontalOptions="End" Margin="3,0,0,0">

            <Label.GestureRecognizers>

                            <TapGestureRecognizer Command="{Binding RemoveEntryCommand, Source={x:Reference MainPage}}" 

                              CommandParameter="{Binding .}"/>

            </Label.GestureRecognizers>

</Label>


SMILET
浏览 33回答 1
1回答

慕侠2389804

不起作用的原因是 XAML 编译查找是特定于页面的,这意味着如果您有两个不同的页面并且使用名称进行搜索,则在大多数情况下它将不起作用。在这种情况下,我通常所做的就是为 BindingContext 使用parent关键字!因此,假设您的标签(位于 ViewCell 中)的父级是 Grid,您可以执行类似的操作Command="{Binding&nbsp;Source={x:Reference&nbsp;parentLayoutGrid},&nbsp;Path=Parent.Parent.BindingContext.RemoveEntryCommand}"所需的父属性数量取决于您的 ViewHeirarchy 以及哪个 View 将具有正确的上下文。祝你好运。如有疑问,请随时回复
打开App,查看更多内容
随时随地看视频慕课网APP