【发布时间】:2016-02-09 10:53:17
【问题描述】:
参考我的previous question,我想知道是否有任何方法可以只更改列表项的背景颜色而不是使用开关控件?
我使用了开关控件来指示多选,但是使用开关控件我会在某些平台上获得此 ON/OFF 文本,这是不必要的,因此我正在寻找更改列表项背景的选项而不是 switch控制。
【问题讨论】:
标签: c# android ios windows-phone xamarin.forms
参考我的previous question,我想知道是否有任何方法可以只更改列表项的背景颜色而不是使用开关控件?
我使用了开关控件来指示多选,但是使用开关控件我会在某些平台上获得此 ON/OFF 文本,这是不必要的,因此我正在寻找更改列表项背景的选项而不是 switch控制。
【问题讨论】:
标签: c# android ios windows-phone xamarin.forms
只需更改Grid BackgroundColor 即列表项ViewCell 的根。
在你的代码中你有:-
public WrappedItemSelectionTemplate()
: base()
{
Grid objGrid = new Grid();
objGrid.BackgroundColor = Color.Gray;
所以您已经将背景设置为灰色。
在视图模型中为背景颜色创建另一个属性,并连接到正在切换的 Switch。然后,您可以将视图模型设置为选择/非选择所需的适当颜色。
然后为上面的objGrid 创建一个绑定,将BackgroundColor 属性绑定到这个ViewModel 属性。
但是,如果您想删除Switch 控件,您将需要执行与前面所述类似的操作。但是,您需要创建一个 TapGestureRecognizer 并将其绑定到 Grid,而不是挂钩到 Switch 切换事件处理程序,以便您可以根据需要更新 ViewModel。
更新 1:-
若要处理 Grid 背景颜色作为特定颜色,您需要创建一个绑定到您的 IsSelected 布尔属性的 IValueConverter,以确定显示为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);
【讨论】:
是的,您可以通过在可绘制对象中添加选择器并在 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" />
为不同的状态(例如按下状态、启用状态等)相应地更改值。
【讨论】: