You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVVMCross框架下MvxListView设置选中项背景色不生效的解决求助

问题根因

你将BackgroundColor绑定写在了MvxListView节点上,该绑定作用于整个列表控件,而非列表内的单个子项,自然无法根据每个子项独立的IsItemSelected属性切换背景色。


可行解决方案

  1. 调整绑定位置
    把背景色绑定从MvxListView节点移除,写到你的子项布局@layout/_product的根控件上,示例如下:
<!-- 这是@layout/_product的示例代码 -->
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    local:MvxBind="BackgroundColor BlackOrBlueColor(IsItemSelected)">
    <!-- 原有子项内容控件保持不变 -->
</LinearLayout>
  1. 补全属性变更通知
    你每个列表项对应的ViewModel需要实现属性变更通知,确保IsItemSelected修改后界面能同步刷新,示例如下:
public class ProductItemViewModel : MvxNotifyPropertyChanged
{
    private bool _isItemSelected;
    public bool IsItemSelected
    {
        get => _isItemSelected;
        set => SetProperty(ref _isItemSelected, value);
    }
    // 其他业务属性
}
  1. 修正选中逻辑
    你的ItemClick命令需要修改对应子项的IsItemSelected状态,示例如下:
// 列表所在的ViewModel中定义命令
public IMvxCommand<ProductItemViewModel> ItemSelectedCommand 
    => new MvxCommand<ProductItemViewModel>(selectedItem =>
    {
        selectedItem.IsItemSelected = !selectedItem.IsItemSelected;
        // 如需维护全局选中集合,可在此处添加对应逻辑
    });
  1. 屏蔽原生列表选中效果
    Android ListView默认自带选中态选择器,会覆盖自定义背景,需要在MvxListView节点添加属性屏蔽默认效果:
<Mvx.MvxListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:choiceMode="multipleChoice"
    android:listSelector="@android:color/transparent"
    local:MvxBind="ItemsSource MyItems; ItemClick ItemSelectedCommand"
    local:MvxItemTemplate="@layout/_product"/>

你现有的BlackOrBlueColorValueConverter代码无需修改,可正常使用。


内容的提问来源于stack exchange,提问作者Kiran Khalkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:30:04