Xamarin.Forms - 在上下文菜单上绑定

Xamarin.Forms - Binding on ContextMenu

我有一个以歌曲为项目的列表。长按元素应显示上下文菜单。

AllSongsViewModel.xaml:

<DataTemplate x:Key="SongTemplate">
    <ViewCell>
        <ViewCell.ContextActions>
            <MenuItem Text="Edit" />
            <MenuItem Text="Delete"/>
        </ViewCell.ContextActions>

        <StackLayout Padding="15,5" VerticalOptions="Center">

            <Label Text="{Binding Title}"
                   FontSize="16"/>
            <Label Text="{Binding Performer}"
                   FontSize="12"/>
        </StackLayout>
    </ViewCell>
</DataTemplate>

效果很好,但我现在需要绑定,以便根据位于 AllSongsViewModel

中的 bool IsAdmin 打开上下文菜单

AllSongsViewModel.cs:

public bool IsAdmin => _authService.LoggedUser.Role == "Admin";

但我不知道如何将此 属性 绑定到上下文菜单

很遗憾,您不能在 ViewModel 上执行此操作。但是您可以在 View Cell 上设置一个 BindingContextChange 事件,然后像这样更改它:

XAML:

<DataTemplate x:Key="SongTemplate">
 <ViewCell BindingContextChanged="OnBindingContextChanged">
    <StackLayout Padding="15,5" VerticalOptions="Center">

        <Label Text="{Binding Title}"
               FontSize="16"/>
        <Label Text="{Binding Performer}"
               FontSize="12"/>
    </StackLayout>
</ViewCell>

在你后面的代码中:

 private void OnBindingContextChanged(object sender, EventArgs e)
    {
        base.OnBindingContextChanged();

        if (BindingContext == null)
            return;

        ViewCell theViewCell = ((ViewCell)sender);
        var viewModel = this.BindingContext.DataContext as AllSongsViewModel;
        theViewCell.ContextActions.Clear();

        if (viewModel.IsAdmin)
        {
            theViewCell.ContextActions.Add(new MenuItem()
            {
                Text = "Delete",
            });

            theViewCell.ContextActions.Add(new MenuItem()
            {
                Text = "Edit",
            });
        }
    }