我得到一个ViewModel
的命令(AddToFavoriteCommand
)并没有被调用。现在它只关注CustomPin class
中的命令,而不是viewModel
。我将viewModel
设置为后面代码中页面的BindingContext
。
但是因为它枚举了我的customPins集合,所以它会在那里查看命令。我需要回到根。我可能需要更改源代码,但无法使其工作。
<ContentPage.Content>
<StackLayout>
<AbsoluteLayout>
<Button Text="{Binding Filter}" Command="{Binding GotoFilterPageCommand}" />
</AbsoluteLayout>
<ListView x:Name="ListView" RowHeight="60" ItemsSource="{Binding CustomPins}" ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Favorite" Command="{Binding AddToFavoriteCommand}" />
<MenuItem Text="..." CommandParameter="{Binding .}" Clicked="OnMoreClicked" />
</ViewCell.ContextActions>
<StackLayout Padding="5" Orientation="Vertical" >
<Label Text="{Binding ParkingLot.Street}" FontSize="Medium" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
代码背后(删除了所有其他逻辑,例如我不需要的点击事件)
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ParkingListPage : ContentPage
{
public ParkingListPage()
{
InitializeComponent();
BindingContext = new ParkingListViewModel();
}
}
我的ViewModel
public class ParkingListViewModel
{
public ParkingListViewModel()
{
AddToFavoriteCommand = new Command(Test);
}
private void Test()
{
}
public IEnumerable<CustomPin> CustomPins { get; set; } = SampleParkings.Parkings;
public Command AddToFavoriteCommand { get; }
}
答案 0 :(得分:7)
试试这样:
<ContentPage x:Name="YourPageName">
<ContentPage.Content>
<StackLayout>
<AbsoluteLayout>
<Button Text="{Binding Filter}" Command="{Binding GotoFilterPageCommand}" />
</AbsoluteLayout>
<ListView x:Name="ListView" RowHeight="60" ItemsSource="{Binding CustomPins}" ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Favorite" Command="{Binding Path=BindingContext.AddToFavoriteCommand, Source={x:Reference YourPageName}}" />
<MenuItem Text="..." CommandParameter="{Binding .}" Clicked="OnMoreClicked" />
</ViewCell.ContextActions>
<StackLayout Padding="5" Orientation="Vertical" >
<Label Text="{Binding ParkingLot.Street}" FontSize="Medium" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
注意我是如何将x:Name
元素添加到页面根目录的。当然,那里有更多的属性,留在那里,但为了清楚起见,我把它们留在了这里。
其次,请注意我是如何从MenuItem
绑定引用该名称并添加Path=BindingContext.
的。这样它就会绑定到名称所标识的元素的BindingContext
,在我们的例子中是ContentPage
。
可在此处找到示例项目:https://github.com/jfversluis/SampleParentBinding