使用背景更改的多 select 列表视图

Multi select list view using background change

参考我的我想知道有没有什么方法可以只改变列表项的背景颜色而不是使用开关控件?

我使用了一个开关控件来指示多项选择,但是有了开关控件,我在某些平台上得到了这个 ON/OFF 文本,这是不必要的,所以我正在寻找更改列表背景的选项项目而不是开关控制。

是的,您可以通过在可绘制对象中添加选择器并在 XML 的列表视图标签中使用 android:listSelector="@drawable/list_selector_background" 来更改列表项的背景。

示例选择器

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_focused="false"
    android:drawable="@drawable/list_item_gradient" />

<!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. -->
<item android:state_focused="true" android:state_enabled="false"
    android:state_pressed="true"
    android:drawable="@drawable/list_selector_background_disabled" />
<item android:state_focused="true" android:state_enabled="false"
    android:drawable="@drawable/list_selector_background_disabled" />

<item android:state_focused="true" android:state_pressed="true"
    android:drawable="@drawable/list_selector_background_transition" />
<item android:state_focused="false" android:state_pressed="true"
    android:drawable="@drawable/list_selector_background_transition" />

<item android:state_focused="true"
    android:drawable="@drawable/list_selector_background_focus" />

相应地更改不同状态的值,例如按下状态、启用状态等。

只需更改 Grid BackgroundColor 即列表项的根 ViewCell

在你的代码中你有:-

public WrappedItemSelectionTemplate()
            : base()
        {

            Grid objGrid = new Grid();
            objGrid.BackgroundColor = Color.Gray;

所以您已经将背景设置为灰色。

在您的视图模型中为背景颜色创建另一个 属性,并连接到正在切换的开关。然后,您可以将视图模型设置为选择/非选择所需的适当颜色。

然后为上面的 objGrid 创建一个绑定 BackgroundColor 属性 绑定到这个 ViewModel 属性.

但是,如果您要删除 Switch 控件,则需要执行与前面所述类似的操作。但是,您需要创建一个 TapGestureRecognizer 并将其绑定到 Grid,而不是连接到 Switch 切换事件处理程序,因此您可以根据需要更新 ViewModel。

更新 1:-

要将 Grid 背景颜色处理为特定颜色,无论是否选择项目,您都需要创建一个 IValueConverter 绑定到您的 IsSelected 布尔值 属性 确定要显示为 Grid.

背景的适当颜色
public class BackGroundColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool)
        {
            if ((bool)value)
            {
                return Color.Green;
            }
            else
            {
                return Color.Gray;
            }
        }
        else
        {
            return Color.Gray;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

}

然后您需要创建一个使用它的 Binding,如下所示:-

objGrid.SetBinding(Grid.BackgroundColorProperty, "IsSelected", converter: new BackGroundColorConverter());

作为一个单独的东西,要删除 Switch,注释以下三行:-

Switch mainSwitch = new Switch();
mainSwitch.SetBinding(Switch.IsToggledProperty, new Binding("IsSelected"));
objGrid.Children.Add(mainSwitch, 2, 0);