I got a ViewModel
用命令(AddToFavoriteCommand
)不会被调用。现在它只关注中的命令CustomPin class
,不是viewModel
。我正在设置我的viewModel
to the BindingContext
后面的代码中的页面。
但由于它枚举了我的自定义引脚集合,因此它会照顾那里的命令。我需要回到根源。我可能需要更改源但无法使其工作。
<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();
}
}
My 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; }
}
试试这样:
<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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)