c# - 为什么我们需要为 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>
解决方案
假设MyCommand
在MyViewModel
命名空间中MyViewModels
,使用Source
RelativeSource
withAncestorType
和x: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 .}"
推荐阅读
- apache-kafka - 当领导者不可用时无法产生消息
- vba - 如何重置自动编号字段的值
- c# - 基于其他行中的单元格值的datagrid WPF中的单元格验证
- java - TreeMap 缺少对象行中的键
- tensorflow - Tensorflow Object Detection API 中多个边界框预测的 IoU 是如何计算的?
- java - 根据两个并行可完成期货的结果执行代码
- java - 在一个 SpringBoot 应用程序中同时使用 JWT 和表单身份验证?
- blockly - 块状的自定义编程语言?
- c - 将第一个数组索引放在数组末尾
- docker - 如何将 https 作为默认而不是 http 添加到 docker 容器?