You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将CollectionView选中项传入父页面ViewModel的命令参数?

实现思路(无需消息传递)

思路1:父VM直接持有子VM引用

让RentalPropertyHomePageVM保留RentalPropertyListVM的实例,直接获取选中项:

  1. 在父VM里声明子VM的属性:
public RentalPropertyListVM RentalPropertyListVM { get; } = new RentalPropertyListVM();
  1. 父页面XAML中把ContentView的BindingContext绑定到该属性:
<local:RentalPropertyListView BindingContext="{Binding RentalPropertyListVM}" />
  1. 父VM的RelayCommand直接从子VM读取选中项:
public IRelayCommand ParentEditCommand => new RelayCommand(() =>
{
    var selected = RentalPropertyListVM.SelectedItem;
    if (selected != null)
    {
        ShowEditPropertyCommand.Execute(selected);
    }
});

思路2:XAML直接绑定选中项

不想在父VM存储子VM的话,通过XAML元素绑定直接传递参数:

  1. 给ContentView内的CollectionView命名:
<CollectionView x:Name="propertyList"
                ItemsSource="{Binding RentalPropertyItems}"
                SelectedItem="{Binding SelectedItem}">
    <!-- 数据模板内容 -->
</CollectionView>
  1. 父页面按钮的命令参数直接绑定这个CollectionView的SelectedItem:
<Button Text="编辑选中项"
        Command="{Binding ShowEditPropertyCommand}"
        CommandParameter="{Binding SelectedItem, Source={x:Reference propertyList}}" />

若ContentView为独立控件,无法直接引用propertyList,可通过父级ContentView的ViewModel获取:

CommandParameter="{Binding BindingContext.SelectedItem, Source={RelativeSource AncestorType={x:Type local:RentalPropertyListView}}}"

思路3:双向绑定共享选中项

在父VM中新增选中项的ObservableProperty,与子VM的SelectedItem做双向绑定,同步选中状态:

  1. 父VM中添加属性:
[ObservableProperty]
private RentalPropertyModel? _selectedProperty;
  1. 子ContentView的SelectedItem双向绑定到父VM的该属性:
<local:RentalPropertyListView SelectedItem="{Binding Source={RelativeSource AncestorType={x:Type local:RentalPropertyHomePage}}, Path=BindingContext.SelectedProperty, Mode=TwoWay}" />
  1. 父VM的按钮命令直接使用自身的SelectedProperty:
public IRelayCommand ParentEditCommand => new RelayCommand(() =>
{
    if (SelectedProperty != null)
    {
        ShowEditPropertyCommand.Execute(SelectedProperty);
    }
});

这几种方法都绕开了消息传递,要么通过VM引用访问数据,要么靠绑定同步状态,完全符合MVVM设计逻辑。

内容的提问来源于stack exchange,提问作者Kev12853

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 18:12:19