Dôn Kayt
Dôn Kayt

Reputation: 103

I want to change background color of each line from my List and display it with Xaml

how can I change the background's color of each line from a List.

e.g :

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

List<string> allLinesTxtList = File.ReadAllLines(path).ToList();

I want to display :

Have someone an idea or maybe a suggestion? Is it possible?

EDIT :

Hey guys, I found a way with the solution of Frenchy, check this out :

Code behind :

 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; }
}

XAML :

        <ListBox Name="lbTodoList" HorizontalContentAlignment="Stretch" 
             IsHitTestVisible="False" AlternationCount="2">
        <ListBox.ItemTemplate>
            <DataTemplate>
                    <TextBlock x:Name="LabelSourceCode" Text="{Binding TextItem}" 
                               Height="Auto" Width="Auto" 
                               FontFamily="Verdana"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Result :

enter image description here Voilà!

Upvotes: 0

Views: 288

Answers (1)

Frenchy
Frenchy

Reputation: 17007

you could use the AlternationCount in xaml code: see this sample with list of strings

<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>

you will have this format:

enter image description here

You could use more than 2 colors if you want

Upvotes: 2

Related Questions