如何更改ListView所选项目的背景颜色?

时间:2016-05-22 09:15:06

标签: xaml xamarin.forms

xaml文件中的ListView结构如下所示。在这个列表视图中,我添加了一些列表项。当我点击此项目中的任何项目时,所选项目的背景颜色默认为橙色。我希望这个选择的iem的背景是黑色的。我怎样才能在xaml中实现这个目标?

<ListView x:Name="LstMenu"
                HasUnevenRows="True">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
            <StackLayout Orientation="Vertical">
                <StackLayout Orientation="Vertical"`enter code here`
                             Padding="10">
                  <Label Text="{Binding ListItems}"
                         FontSize="15"
                         TextColor="White"
                         HorizontalTextAlignment="Start"
                         VerticalTextAlignment="Center" />
                </StackLayout>
                <Grid BackgroundColor="Black"
                      HeightRequest="1"/>
              </StackLayout>
              </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>

1 个答案:

答案 0 :(得分:0)

我真的希望这个问题有一个很好的跨平台解决方案,但到目前为止我还没找到。这是Xamarin.Forms Forums中几乎完全相同的问题的链接。以Android项目为例,我通常通过将一个styles.xml文件添加到Resources目录来实现您正在寻找的效果:

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <color name="CustomHighlight">@android:color/transparent</color>
  <style name="Theme.Splash" parent="android:Theme">
    <item name="android:windowBackground">@drawable/androidsplash</item> <!-- must be lowercase -->
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsTranslucent">false</item>
    <item name="android:windowIsFloating">false</item>
    <item name="android:backgroundDimEnabled">true</item>
  </style>
  <style name="CustomTheme" parent="android:Theme.Holo">
    <item name="android:icon">@android:color/transparent</item>
    <item name="android:colorPressedHighlight">@color/CustomHighlight</item>
    <item name="android:colorLongPressedHighlight">@color/CustomHighlight</item>
    <item name="android:colorFocusedHighlight">@color/CustomHighlight</item>
    <item name="android:colorActivatedHighlight">@color/CustomHighlight</item>
    <item name="android:activatedBackgroundIndicator">@color/CustomHighlight</item>
    <!--<item name="android:colorActivatedHighlight">@android:color/transparent</item>-->
  </style>
  <style name="ProgressBarStyle" parent="@android:style/Widget.ProgressBar.Horizontal"/>
</resources>

请注意,我在这种情况下使用系统定义的颜色(透明),但您可以引用或定义您喜欢的任何颜色。然后在MainActivity.cs文件中添加对该样式的引用:

[Activity(Label = Constants.CompanyName,
          Theme = "@style/CustomTheme",
          Icon = "@drawable/icon",
          MainLauncher = false,
          ScreenOrientation = ScreenOrientation.Portrait,
          ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
   // your code here
}

我没有为Windows或iOS提供方便的示例,但概念是相同的;覆盖特定于平台的项目中的默认样式。

相关问题