简体   繁体   English

更改列表视图项的背景颜色

[英]Change the background color of listview items

I want to change the background color of listview alternate rows.我想更改列表视图备用行的背景颜色。 I am binding values to listview through ObservableCollection.我正在通过 ObservableCollection 将值绑定到列表视图。 So that I can't iterate through listview items.这样我就无法遍历列表视图项。 It shows:表明:

`System.InvalidCastException: 'Unable to cast object of type 'xx.StudentClass' to type 'Windows.UI.Xaml.Controls.ListViewItem'.' `System.InvalidCastException: '无法将类型'xx.StudentClass' 的对象转换为类型'Windows.UI.Xaml.Controls.ListViewItem'。'

ObservableCollection<StudentClass> StudentData = new ObservableCollection<StudentClass>();
var statement = connection.Prepare("SELECT name,ID from student_details");

while (!(SQLiteResult.DONE == statement.Step()))
{
    if (statement[0] != null)
    {                     
        StudentClass c1 = new StudentClass() { studentName= statement[0].ToString, studentID= statement[1].ToString};
        StudentData.Add(c1);
    }
}

StudentListview.ItemsSource = StudentData;
ChangeBgColor();

private void ChangeBgColor()
{
    int counter = 1;

    foreach (ListViewItem item in this.StudentListview.Items)
    {
        if (counter % 2 == 0)
        {
            item.Background = new SolidColorBrush(Colors.Orange);
        }
        else
        {
            item.Background = new SolidColorBrush(Colors.OrangeRed);
        }
        counter++;
    }
}

<ListView x:Name="StudentListview" Visibility="Collapsed"    VerticalAlignment="Top" HorizontalAlignment="Right" Height="250px"  Width="550px">
  <ListView.ItemTemplate >
    <DataTemplate>
      <Grid>
        <StackPanel Orientation="Vertical" >
          <StackPanel Orientation="Horizontal">
            <TextBlock Foreground="Black" Text="{Binding studentName}"  FontSize="20"  Width="350px" TextWrapping="Wrap"></TextBlock>
          </StackPanel>
          <StackPanel Orientation="Horizontal">                                                              
            <TextBlock Foreground="Black" Text="{Binding  studentID}"  FontSize="20" Width="350px" TextWrapping="Wrap" ></TextBlock>
          </StackPanel>
      </Grid>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

If you want this to tackle in a future proof way, I would suggest creating a new ListView control that can handle this...如果您希望以未来证明的方式解决此问题,我建议创建一个可以处理此问题的新ListView控件...

Here is how I did this, first define the new control with following properties这是我这样做的方法,首先定义具有以下属性的新控件

public class AlternatingListView : ListView
{
    public static readonly DependencyProperty OddRowBackgroundProperty = DependencyProperty.Register(
        nameof(OddRowBackground),
        typeof(Brush),
        typeof(AlternatingListView),
        new PropertyMetadata(null));

    public static readonly DependencyProperty EvenRowBackgroundProperty = DependencyProperty.Register(
        nameof(EvenRowBackground),
        typeof(Brush),
        typeof(AlternatingListView),
        new PropertyMetadata(null));

    public Brush OddRowBackground
    {
        get { return (Brush)GetValue(OddRowBackgroundProperty); }
        set { SetValue(OddRowBackgroundProperty, (Brush)value); }
    }

    public Brush EvenRowBackground
    {
        get { return (Brush)GetValue(EvenRowBackgroundProperty); }
        set { SetValue(EvenRowBackgroundProperty, (Brush)value); }
    }

    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        base.PrepareContainerForItemOverride(element, item);
        ListViewItem listViewItem = element as ListViewItem;

        if (listViewItem == null)
        {
            return;
        }

        int index = IndexFromContainer(element);
        listViewItem.Background = (index + 1) % 2 == 1 ? OddRowBackground : EvenRowBackground;
    }
}

With all this in place you can add that control your XAML and define the needed colors.有了所有这些,您可以添加控制您的 XAML 并定义所需的颜色。

  <controls:AlternatingListView x:Name="ListView"
                                ItemsSource="{x:Bind Items}"
                                EvenRowBackground="SlateGray"
                                OddRowBackground="White" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM