如何将CollectionView选中项传入父页面ViewModel的命令参数?
实现思路(无需消息传递)
思路1:父VM直接持有子VM引用
让RentalPropertyHomePageVM保留RentalPropertyListVM的实例,直接获取选中项:
- 在父VM里声明子VM的属性:
public RentalPropertyListVM RentalPropertyListVM { get; } = new RentalPropertyListVM();
- 父页面XAML中把ContentView的
BindingContext绑定到该属性:
<local:RentalPropertyListView BindingContext="{Binding RentalPropertyListVM}" />
- 父VM的RelayCommand直接从子VM读取选中项:
public IRelayCommand ParentEditCommand => new RelayCommand(() => { var selected = RentalPropertyListVM.SelectedItem; if (selected != null) { ShowEditPropertyCommand.Execute(selected); } });
思路2:XAML直接绑定选中项
不想在父VM存储子VM的话,通过XAML元素绑定直接传递参数:
- 给ContentView内的CollectionView命名:
<CollectionView x:Name="propertyList" ItemsSource="{Binding RentalPropertyItems}" SelectedItem="{Binding SelectedItem}"> <!-- 数据模板内容 --> </CollectionView>
- 父页面按钮的命令参数直接绑定这个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做双向绑定,同步选中状态:
- 父VM中添加属性:
[ObservableProperty] private RentalPropertyModel? _selectedProperty;
- 子ContentView的
SelectedItem双向绑定到父VM的该属性:
<local:RentalPropertyListView SelectedItem="{Binding Source={RelativeSource AncestorType={x:Type local:RentalPropertyHomePage}}, Path=BindingContext.SelectedProperty, Mode=TwoWay}" />
- 父VM的按钮命令直接使用自身的
SelectedProperty:
public IRelayCommand ParentEditCommand => new RelayCommand(() => { if (SelectedProperty != null) { ShowEditPropertyCommand.Execute(SelectedProperty); } });
这几种方法都绕开了消息传递,要么通过VM引用访问数据,要么靠绑定同步状态,完全符合MVVM设计逻辑。
内容的提问来源于stack exchange,提问作者Kev12853
相关产品推荐
相关产品推荐

