【问题标题】:How to bind Image Button command from a DataTemplate Selector to a ViewModel?如何将图像按钮命令从 DataTemplate 选择器绑定到 ViewModel?
【发布时间】:2019-12-27 05:04:37
【问题描述】:

我正在与SyncFusion's TreeView 合作。我有一个带有三个单独的数据模板/自定义视图单元的 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>

我现在正在尝试将我的命令从我的一个数据模板(下面的代码)绑定到连接到我的页面的视图模型,但我似乎无法连接我的数据绑定。大多数在线示例在视图/视图模型的同一 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}" 
                                 />  

【问题讨论】:

    标签: c# xamarin xamarin.forms prism syncfusion


    【解决方案1】:

    试试这个,可能你错过了命令的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

    在这里找到Reference

    【讨论】:

    • 如何从不同的 .xaml 文件中引用树视图?我正在尝试处理我的 SamplePageViewModel 中的操作。我像你提到的那样添加了引用 SamplePage 的代码,但它仍然不起作用 =(
    • 在这种情况下,您应该将 SampleTemplate 的内容页面(父内容页面)的 x:name 指定为 x:reference
    【解决方案2】:

    您可能希望列表数据模板中的代码直接从您的视图模型中调用命令并将当前项目传递给视图模型以执行必要的操作,我建议您可以看看:

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

    1.我们需要在列表数据模板中创建属性。这些属性将包含其父视图的 BindingContext 并且将从它们获取命令。

    2.将绑定上下文从 xaml 传递到数据模板

    3.接收数据模板中的绑定上下文,绑定命令并将当前项作为命令的参数传递。

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 2012-09-03
      • 2021-10-25
      • 2016-11-22
      • 1970-01-01
      • 2011-09-17
      相关资源
      最近更新 更多