c# - 更改背景颜色 selecteditem Listview

标签 c# xamarin.forms

我对 Xamarin.Forms 中的 ListView 有疑问 将我的 ListView 与一些项目成功绑定(bind),但我想更改所选单元格的背景颜色我如何在 Xamarin.Forms 中执行此操作

我利用

var cell = DataTemplate(typeof(ImageCell));

ListView listView = new ListView
{
    SeparatorColor = Color.Green,
    ItemsSource = ListlvData,
    ItemTemplate = cell, // Set the ImageCell to the item templatefor the listview
};

最佳答案

编辑 2:

有时候,如果我遇到奇怪的问题,我的 ViewCellBackgroundColor 永远不会变回原来的颜色,所以我开始这样做来改变颜色:

cell.Tapped += async (sender, args) => {
    cell.View.BackgroundColor = Color.Red;

#pragma warning disable 4014 //These pragma's are only needed if your Tapped is being assigned an async anonymous function and muffles the compiler warning that you did not await Task.Run() which you do not want to fire and forget it

    Task.Run(async () => {     //Change the background color back after a small delay, no matter what happens
        await Task.Delay(300); //Or how ever long to wait

        Device.BeginInvokeOnMainThread(() => cell.View.BackgroundColor = Color.Default); //Turn it back to the default color after your event code is done
    });

#pragma warning restore 4014

    await OnListViewTextCellTapped(cell); //Run your actual `Tapped` event code

};

编辑:

要将以下代码添加到 ListView.DataTemplate,您需要执行如下操作:

ListView listView = new ListView {
    SeparatorColor = Color.Green,
    ItemsSource    = ListlvData
};

listView.ItemTemplate = new DataTemplate(() => {
    ViewCell cell = new ViewCell();

    cell.Tapped += (sender, args) => {
        cell.View.BackgroundColor = Color.Red;
        OnListViewTextCellTapped(cell);            //Run your actual `Tapped` event code
        cell.View.BackgroundColor = Color.Default; //Turn it back to the default color after your event code is done
    };

    cell.View = new Image();

    return cell;
});

要更改 Tapped 的背景颜色,您需要在其中使用 ViewCellImage 控件,因为 ImageCell 默认不支持 BackgroundColor

我在 ViewCell 中放置了一个 StackLayout 但随后在 Tapped 事件中,我更改了 ViewCell.ViewBackgroundColor,像这样:

ViewCell cell = new ViewCell();

cell.Tapped += (sender, args) => {
    cell.View.BackgroundColor = Color.Red;
    OnListViewTextCellTapped(cell);            //Run your actual `Tapped` event code
    cell.View.BackgroundColor = Color.Default; //Turn it back to the default color after your event code is done
};

关于c# - 更改背景颜色 selecteditem Listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33169851/

相关文章:

xamarin - 如何在 Xamarin.Forms 中检测设备的屏幕方向?

c# - 使用 MVVM 架构从 SignaturePadView 检索图像

c# - MVC 日期时间模型绑定(bind)

c# - 如何修复 "a connection attempt failed because the connected party did not properly respond after a period of time ..."错误?

c# - 在 MVC4 中绑定(bind) ListBoxFor 控件时出错

c# - 如何使用 CSharpCodeProvider 定位 .net 4.5?

c# - 如何显示 windows phone 8.1 通用商店应用程序的加载动画?

c# - 使用 Xamarin.Forms 创建一个每个单元格都是方形的 3X2 网格

c# - 在 Xamarin Forms 中渲染 HTML 并从 HTML 链接打开嵌入的 PDF

c# - Xamarin XAML ListView - 如何以编程方式选择