【问题标题】:Why we need to set binding path and source xReference for Command and not just the property/command name?为什么我们需要为 Command 设置绑定路径和源 xReference 而不仅仅是属性/命令名称?
【发布时间】:2020-08-21 17:31:45
【问题描述】:

ListView --> ItemSource = { Binding Items } //Works

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


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

Command="{Binding Path=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>

【问题讨论】:

  • Items 中每个 Item 的 ViewModel 是否有 MarkAsCompleted 方法?或者MarkAsCompletedCommand 在哪里?
  • MarkasCompleted 在 vi​​ewmodel 类中,我有一个单独的 todoItem 类,它将一个 todoitem 对象列表发送到 viewmodel。不是每个 ToDoItem 都有这个功能。 (我的意思是标记完成功能不在 ToDoItem 类中,它是 viewmodel 类中的常见功能)。

标签: c# xamarin xamarin.forms


【解决方案1】:

假设MyCommand 位于命名空间MyViewModels 中的MyViewModel 中,请使用Source RelativeSourceAncestorTypex:Type

CommandCommandParameter 下方的Bindings 分别指MyViewModelListView.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 .}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多