c# - Xamarin.Forms - ContextMenu 上的绑定(bind)

标签 c# mvvm xamarin.forms contextmenu datatemplate

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

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>

这很好用,但我现在需要绑定(bind),以便根据 bool IsAdmin 打开上下文菜单,它位于 AllSongsViewModel

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

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

最佳答案

不幸的是,您不能在 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",
            });
        }
    }

关于c# - Xamarin.Forms - ContextMenu 上的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61318610/

相关文章:

c# - 如何使用正则表达式在C#中查找和替换“@@ word @@”?

c# - 您如何编写匹配除第一次出现以外的所有内容的正则表达式?

wpf - 在WPF MVVM Prism应用程序中使用OnPropertyChanged和发布之间有什么区别?

c# - 使用 mvvm 在 xamarin 上绑定(bind)数据收集

c# - Xamarin Forms IOS - MKUserTrackingButton 位置

c# - 如何解决循环依赖

c# - 如何防止 Visual Studio 缩进换行符 (C#)?

c# - 在 RaisePropertyChangedEvent 之后 ListView 不更新

c# - iOS 设备上缺少日期时间解析

ios - UINavigationBar.Appearance.BarTintColor 也影响我的标签栏背景颜色