如何将命令从 ViewModel 绑定到不在自己文件中的 DataTemplate
How to bind command from ViewModel to a DataTemplate which is in in't own file
我正在使用带有 ItemTemplateSelector 的可绑定堆栈布局。我的 DataTemplates 在另一个文件中,该文件是作为 MergedResourceDictionay 包含在 MainView 中的 ResourceDictionary。在我的一个 DataTemplates 中,我有一个带有 TapGestureRecognizer 的标签,它应该在 MainViewViewModel 中触发命令,但我似乎无法工作....
我尝试在我的命令绑定中使用 Source={x:Reference MainPage}
,但无法引用它,因为它不在同一个文件中
(Xamarin.Forms.Xaml.XamlParseException: 'Position 28:51. Can not find
the object referenced by 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>
不起作用的原因是 XAML 编译查找是特定于页面的,这意味着如果您有两个不同的页面并且您使用名称进行搜索,那么在大多数情况下它将不起作用。
在这种情况下,我通常会为我的 BindingContext 使用 parent 关键字!
因此假设您的 Label(在 ViewCell 中)有一个 Grid 父级,您可以执行类似
的操作
Command="{Binding Source={x:Reference parentLayoutGrid}, Path=Parent.Parent.BindingContext.RemoveEntryCommand}"
所需的父属性数量取决于您的 ViewHeirarchy 以及哪个 View 具有正确的上下文。
祝你好运。
如有疑问,请随时回来
我正在使用带有 ItemTemplateSelector 的可绑定堆栈布局。我的 DataTemplates 在另一个文件中,该文件是作为 MergedResourceDictionay 包含在 MainView 中的 ResourceDictionary。在我的一个 DataTemplates 中,我有一个带有 TapGestureRecognizer 的标签,它应该在 MainViewViewModel 中触发命令,但我似乎无法工作....
我尝试在我的命令绑定中使用 Source={x:Reference MainPage}
,但无法引用它,因为它不在同一个文件中
(Xamarin.Forms.Xaml.XamlParseException: 'Position 28:51. Can not find the object referenced by 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>
不起作用的原因是 XAML 编译查找是特定于页面的,这意味着如果您有两个不同的页面并且您使用名称进行搜索,那么在大多数情况下它将不起作用。
在这种情况下,我通常会为我的 BindingContext 使用 parent 关键字!
因此假设您的 Label(在 ViewCell 中)有一个 Grid 父级,您可以执行类似
的操作Command="{Binding Source={x:Reference parentLayoutGrid}, Path=Parent.Parent.BindingContext.RemoveEntryCommand}"
所需的父属性数量取决于您的 ViewHeirarchy 以及哪个 View 具有正确的上下文。
祝你好运。
如有疑问,请随时回来