【问题标题】:Xamarin.Forms ListView change Cell on ContextMenu openXamarin.Forms ListView 在 ContextMenu 打开时更改单元格
【发布时间】:2017-04-28 22:34:05
【问题描述】:

我使用 Xamarin.Forms 来定义 ListView。这个ListViewViewCell 内部定义了一些ContextActions。然后根据平台,将这些上下文操作呈现给用户。在 Android 中,这是通过长按特定项目来触发的。遗憾的是,该项目不会(正确)突出显示,如此屏幕截图所示(我长按第三个​​项目,遗憾的是我还无法嵌入图像)。

有没有办法在上下文菜单打开时修改单元格?专门要求为 Android 提供解决方案,但也欢迎提供一般性答案。最终的目标是改进突出显示,例如通过更改单元格的背景颜色。修改单元格,当按下一个 ContextAction 时,不是我想要的。

我浏览了 Xamarin.Forms 的源代码,并考虑以某种方式从例如继承。 ViewCell 类,但找不到将在长按项目时触发/调用的事件或命令。我已经建立了一个简单的存储库来说明行为:GitHub repository

最重要的代码sn-ps

  • XAML 中的 ListView 定义

    <?xml version="1.0" encoding="utf-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:ListViewContextMenu" x:Class="ListViewContextMenu.ListViewContextMenuPage">
        <ListView x:Name="MyListView">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.ContextActions>
                            <MenuItem Text="Action" Command="{Binding OnAction}" CommandParameter="{Binding .}"/>
                        </ViewCell.ContextActions>
                        <Label Text="{Binding Name}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage>
    
  • MyItem 定义 (MVVM)

    using System.Diagnostics;
    using Xamarin.Forms;
    
    namespace ListViewContextMenu
    {
        public class MyItem
        {
            public string Name { get; set; }
            public Command OnAction { get; set; }
    
            public MyItem()
            {
                OnAction = new Command((obj) => Debug.WriteLine($"Item {obj.ToString()} clicked"));
            }
        }
    }
    

【问题讨论】:

  • 识别长按手势何时发生可能是一个很好的方法。您是否查看过 Xlabs 如何检测到 LongPress? github.com/XLabs/Xamarin-Forms-Labs/…
  • 您可以使用自定义渲染器或效果来手动处理项目长按例如:Control.ItemLongClick += Control_ItemLongClick;您可以在其中自定义外观

标签: c# listview xamarin.forms listviewitem


【解决方案1】:

无需自定义渲染器 - 您只需将以下标记添加到 styles.xml(位置:Android 项目 > 资源 > 值 > styles.xml

<style name="MyTheme" parent="MyTheme.Base">
  <item name="android:colorLongPressedHighlight">@color/ListViewHighlighted</item>
</style>
<color name="ListViewHighlighted">#A8A8A8</color>

更多详情请访问post

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 2010-12-23
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多