【发布时间】:2017-10-30 09:36:05
【问题描述】:
我想更改列表视图交替行的背景颜色。我通过 ObservableCollection 将值绑定到列表视图。这样我就无法遍历 listview 项目。它显示:
`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>
【问题讨论】:
-
重新格式化您的代码后,我发现您在外部
StackPanel上缺少一个结束标记。 -
如果您需要扩展控件以处理悬停和按下时的不同颜色 - here