簡體   English   中英

如何將圖像按鈕命令從DataTemplate選擇器綁定到ViewModel?

[英]How to bind Image Button command from a DataTemplate Selector to a ViewModel?

我正在使用SyncFusion的TreeView 我有一個帶有三個單獨的DataTemplate / Custom View單元的TreeView。 在我的主要XAML中,下面有綁定到我的DataTemplates的以下樹視圖代碼。

SamplePage.xaml

<syncfusion:SfTreeView x:Name="treeView"
       QueryNodeSize="TreeView_QueryNodeSize"
       NodeSizeMode="Dynamic"
       AutoExpandMode="RootNodesExpanded"
       ChildPropertyName="SubFiles"
       ItemsSource="{Binding ImageNodeInfo}" Indentation="0" 
       ItemTemplate="{StaticResource TemplateSelector}">
</syncfusion:SfTreeView>

我現在正在嘗試將命令從我的數據模板之一(下面的代碼)綁定到連接到頁面的視圖模型,但是我似乎無法連接數據綁定。 在線大多數示例在view / viewModel的同一xaml頁面上顯示數據模板。 但是,我的代碼使用的是數據模板選擇器,這給了我更難的綁定途徑。

SampleTemplate.xaml

<ViewCell.BindingContext>
    <local:SamplePage x:Key="SamplePage">
    </local:SamplePage>
</ViewCell.BindingContext>



   <ImageButton Aspect="AspectFill"
      Grid.Row="0" Grid.Column="3" 
      HorizontalOptions="End" 
      WidthRequest="90" HeightRequest="90" 
      Source="{xaml:ImageResource plus_Icon}"
      Command="{Binding Path=BindingContext.AddAsJobClickedCommand}, Source={x:Reference SamplePage}" 
      CommandParameter="{Binding treeView}" 
                                 />  

您可能希望列表數據模板中的代碼可以直接從視圖模型中調用命令,並將當前項傳遞給視圖模型以執行必要的操作,建議您看一下:

https://doumer.me/xamarin-forms-listview-advanced-guide-with-mvvm/

1.我們需要在列表數據模板中創建屬性。 這些屬性將包含其父視圖的BindingContext,並從中獲取命令。

2將Binding上下文從xaml傳遞到數據模板

3.接收數據模板中的綁定上下文,綁定命令,並將當前項作為命令的參數傳遞。

嘗試此操作,可能您缺少該命令的x:Reference

<ImageButton Aspect="AspectFill"
             Grid.Row="0" Grid.Column="3" 
             HorizontalOptions="End" 
             WidthRequest="90" HeightRequest="90" 
             Source="{xaml:ImageResource plus_Icon}"
             Command="{Binding Path=BindingContext.AddAsJobClickedCommand, Source={x:Reference treeView}}"
             CommandParameter="{x:Reference treeView}"/>

注意:這里treeView是SfTreeView的x:Name

在這里找到參考

暫無
暫無

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

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