我有viewmodel和view,它在ListView中列出了我的Model对象,每个列表条目都包含两个按钮:详细信息和预订。
查看
<ListView
ItemsSource="{Binding Models}">
<ListView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Button Command="{Binding Delete}"></Button>
<Button Command="{Binding Details}"></Button>
</StackLayout>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ViewModel
class ModelsViewModel : MvxViewModel
{
private ObservableCollection<Model> models;
public ObservableCollection<Model> Models
{
get
{
return models;
}
set
{
SetProperty(ref models, value);
}
}
private IMvxCommand details;
public IMvxCommand Details
{
get
{
details = details ?? new MvxCommand<ListItem>(o =>
{
});
return details;
}
}
private IMvxCommand delete;
public IMvxCommand Delete
{
get
{
delete = delete ?? new MvxCommand<ListItem>(o =>
{
});
return delete;
}
}
}
这些按钮中的每一个都应该调用ModelsViewModel中Details/Delete方法中的lambda。
然而,listview中的数据绑定指向不存在此类方法的Model对象。我的问题是,有没有一种方法可以更改listview中项目的绑定上下文,并将单击的项目作为参数传递?
我试图扰乱Source并设置BindingContext,但没有成功
这样尝试:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="parentContePage">
<ListView ItemsSource="{Binding Models}">
<ListView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Button Command="{Binding Source={x:Reference parentContePage}, Path=BindingContext.Delete}"
CommandParameter="{Binding .}"/>
<Button Command="{Binding Source={x:Reference parentContePage}, Path=BindingContext.Details}"
CommandParameter="{Binding .}"/>
</StackLayout>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
确保将x:Name
提供给您的父内容页,如上所述。
首先,我还可以发表评论,所以我会发布一个答案。尝试将命令从MvxCommand<ListItem>
更改为MvxCommand<Model>
,因为命令参数在遵循上一个答案后采用当前模型。