首页 > 解决方案 > 为什么我们需要为 Command 设置绑定路径和源 xReference 而不仅仅是属性/命令名称?

问题描述

ListView --> ItemSource = { Binding Items } //有效

MenuItem --> Command={ Binding MarkAsCompleted } // 不工作


仅在我添加路径和源时才有效

Command="{绑定路径=BindingContext.MarkAsCompletedCommand, Source={x:Reference TodoViewPage}}"

为什么会这样?!?

<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
 <ListView.ItemTemplate>
  <DataTemplate>
   <ViewCell>
    <ViewCell.ContextActions>
     <MenuItem Text="Complete" Command="{Binding Path=BindingContext.MarkAsCompletedCommand, Source={x:Reference TodoViewPage}}" CommandParameter="{Binding .}"/>
    </ViewCell.ContextActions>
    <StackLayout>
     <Label Text="{Binding Name}"></Label>
    </StackLayout>
   </ViewCell>
  </DataTemplate>
 </ListView.ItemTemplate>
</ListView>

标签: c#xamarinxamarin.forms

解决方案


假设MyCommandMyViewModel命名空间中MyViewModels,使用Source RelativeSourcewithAncestorTypex:Type

Command和下面分别CommandParameter Bindings指的是MyViewModel和中的项ListView.ItemsSource

xmlns:vm="clr-namespace:MyViewModels"
...
<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
         ...
           Command="{Binding Source={RelativeSource AncestorType={x:Type vm:MyViewModel}}, 
                             Path=MyCommand}"
           CommandParameter="{Binding .}"

推荐阅读