C# 我想更改列表中每一行的背景色,并用Xaml显示它

C# 我想更改列表中每一行的背景色,并用Xaml显示它,c#,wpf,xaml,C#,Wpf,Xaml,如何更改列表中每行的背景颜色 e、 g: String path = @"D:\code.cs"; List<string> allLinesTxtList = File.ReadAllLines(path).ToList(); stringpath=@“D:\code.cs”; List allLinesTxtList=File.ReadAllLines(path.ToList(); 我想展示: 第一行背景=“绿色” 第二行背景=“灰色” 第三行背景=“绿色” 第四行背景=

如何更改列表中每行的背景颜色

e、 g:

String path = @"D:\code.cs";

List<string> allLinesTxtList = File.ReadAllLines(path).ToList();
stringpath=@“D:\code.cs”;
List allLinesTxtList=File.ReadAllLines(path.ToList();
我想展示:

  • 第一行背景=“绿色”
  • 第二行背景=“灰色”
  • 第三行背景=“绿色”
  • 第四行背景=“灰色”
  • …绿色…灰色…等等
有人有什么想法或建议吗?可能吗

编辑:

嘿,伙计们,我找到了一个解决法兰西问题的方法,看看这个:

代码隐藏:

 using (StreamReader sr = new StreamReader(path))
        {
            for (int i = 0; i <= allLinesTxtList.Count; i++)
            {
                String line = sr.ReadLine();
                Console.WriteLine(line);
                items.Add(new TodoItem() {TextItem = line});
            }
            lbTodoList.ItemsSource = items;
        }

public class TodoItem
{
    public string TextItem { get; set; }
}
使用(StreamReader sr=新的StreamReader(路径))
{
对于(inti=0;i您可以使用in-xaml代码:请参阅此示例和字符串列表

<Window.Resources>
        <Style  TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="#19f39611"></Setter>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="#19000000"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
</Window.Resources>

<ListBox x:Name="lbPersonList" Margin="19,17,162,25" AlternationCount="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>

您将拥有以下格式:

如果需要,可以使用两种以上的颜色

您可以使用in-xaml代码:请参阅此示例和字符串列表

<Window.Resources>
        <Style  TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="#19f39611"></Setter>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="#19000000"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
</Window.Resources>

<ListBox x:Name="lbPersonList" Margin="19,17,162,25" AlternationCount="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>

您将拥有以下格式:


如果您想要

使用
索引%2==0
在绿色/grey@Jawad我试过这样做,但没有效果。但是我如何才能得到每一行的索引呢?对于(inti=1;I索引%2==0
在绿色/grey@Jawad我用这种方法尝试了,但不起作用。但是如何获取每行的索引呢?for(int I=1;I