MAUI中CollectionView.Footer按钮绑定ViewModel命令失败求助
CollectionView的Footer默认继承了CollectionView的绑定上下文(也就是ItemsSource中的SomeModel实例),所以直接绑定SomeCommand会找不到ViewModel里的命令,下面是两种可行的解决方法:
方法一:通过RelativeSource关联ContentPage的ViewModel
修改Footer内Button的Command绑定,利用RelativeSource向上定位到父级ContentPage,直接引用它的BindingContext(也就是你的SomePageViewModel):
<Button Padding="0" CornerRadius="10" HeightRequest="35" WidthRequest="60" BackgroundColor="#FF8787" FontFamily="geometria_medium" FontSize="24" HorizontalOptions="End" Text="+" Command="{Binding BindingContext.SomeCommand, RelativeSource={RelativeSource AncestorType={x:Type ContentPage}}}" />
方法二:给ContentPage命名后用x:Reference绑定
- 先给ContentPage添加
x:Name属性:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewmodels="clr-namespace:Paraglider.MobileApp.ViewModels" xmlns:models="clr-namespace:Paraglider.MobileApp.Models" x:Class="Paraglider.MobileApp.Pages.SomePage" x:DataType="viewmodels:SomePageViewModel" x:Name="CurrentPage"> <!-- 新增命名 -->
- 再修改Button的绑定语句:
<Button Padding="0" CornerRadius="10" HeightRequest="35" WidthRequest="60" BackgroundColor="#FF8787" FontFamily="geometria_medium" FontSize="24" HorizontalOptions="End" Text="+" Command="{Binding BindingContext.SomeCommand, Source={x:Reference CurrentPage}}" />
额外提示:ViewModel中的笔误
你的SomePageViewModel的InitAsync方法里存在两处错误:
SomeModels = new ObservableCollection<SomeModels>(components);
需修正为:
SomeModels = new ObservableCollection<SomeModel>(someModels);
(泛型参数应为SomeModel,且构造函数参数要对应前面获取的someModels变量)
内容的提问来源于stack exchange,提问作者diukin
相关产品推荐
相关产品推荐

