簡體   English   中英

如何將 ViewModel 中的命令綁定到不屬於自己的文件中的 DataTemplate

[英]How to bind command from ViewModel to a DataTemplate which is in in't own file

我正在使用帶有 ItemTemplateSelector 的可綁定堆棧布局。 我的 DataTemplates 在另一個文件中,該文件是 MainView 中作為 MergedResourceDictionay 包含的 ResourceDictionary。 在我的一個 DataTempplates 中,我有 Label 和 TapGestureRecognizer,它應該在 MainViewViewModel 中觸發命令,我似乎無法開始工作......

我嘗試在我的命令綁定中使用Source={x:Reference MainPage} ,但由於它不在同一個文件中,所以無法引用它

(Xamarin.Forms.Xaml.XamlParseException:'位置 28:51。找不到 MainPage 引用的 object')

<--! 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 中)有一個父級,它是一個網格,您可以執行類似的操作

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

所需的父屬性數量取決於您的 ViewHierarchy 以及哪個 View 將具有正確的上下文。

祝你好運。

如有疑問,請隨時回復

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM