@qubuss 在下面给出了正确答案,但我想提供更多上下文并展示一个示例以使其更清楚:
让我们考虑以下页面:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="firstPage" -->this reference parent context
x:Class="Your_Class_Name">
<ListView x:Name="ListSource"
ItemsSource="{Binding ListSource}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
// this come from item source
<Label Text="{Binding ABC}"></Label>
<Button Command="{Binding BindingContext.CommandFromParent
, Source={x:Reference firstPage} }" />
</Grid>
</ViewCell>
/DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
你的视图模型应该是这样的
public class ViewModelName
{
private List<YourDataType> _listSource = new List<YourDataType>();
public List<YourDataType> ListSource
{
get => _listSource;
set
{
_listSource = value;
RaisePropertyChanged();
}
}
public ICommand CommandFromParent => new Command(HandleYourActionHere);
}
}
解释
当我们写的时候BindingContext.CommandFromParent
,BindingContext 代表 BindingContextfirstPage(x:Name="firstPage")
的类型ViewModelName