为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
SMILET 2024-01-20 21:17:18
我正在使用带有 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>
查看完整描述

1 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

不起作用的原因是 XAML 编译查找是特定于页面的,这意味着如果您有两个不同的页面并且使用名称进行搜索,则在大多数情况下它将不起作用。

在这种情况下,我通常所做的就是为 BindingContext 使用parent关键字!

因此,假设您的标签(位于 ViewCell 中)的父级是 Grid,您可以执行类似的操作

Command="{Binding Source={x:Reference parentLayoutGrid}, Path=Parent.Parent.BindingContext.RemoveEntryCommand}"

所需的父属性数量取决于您的 ViewHeirarchy 以及哪个 View 将具有正确的上下文。

祝你好运。

如有疑问,请随时回复


查看完整回答
反对 回复 2024-01-20
  • 1 回答
  • 0 关注
  • 28 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信