hasdrubal
hasdrubal

Reputation: 1148

Change appearance rows in WPF ListView c# window

In my windows application I defined a window with a list. There are items in this list based on the binder (for the moment I put in the items programmatically).

<ListView x:Name="event_list" IsEnabled="False">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Path=Type}"/>
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}"/>
        </GridView>
    </ListView.View>
</ListView>

var row = new { Type = "type", Description = "description" };
event_list.Items.Add(row);

Lets say I want to change the 3rd row and make the font weight bold, how do I achieve this?

Clearly, the following doesn't compile:

event_lits.Items[2].FontWeight = FontWeights.Bold;

Because the Items propperty returns only the strings I put in, not the view object of the row itself.

Notes for eager answerers: In a wpf window, a ListView is this class, not this class (the reason why 9/10 google searches on this topic fails).

Upvotes: 1

Views: 117

Answers (1)

mm8
mm8

Reputation: 169330

You could add an ItemContainerStyle with a DataTrigger that binds to a property of the data object:

<ListView x:Name="event_list" IsEnabled="False">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsBold}" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Path=Type}"/>
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}"/>
        </GridView>
    </ListView.View>
</ListView>

Sample data:

event_list.Items.Add(new { Type = "type", Description = "description" });
event_list.Items.Add(new { Type = "type", Description = "description" });
event_list.Items.Add(new { Type = "type", Description = "description", IsBold = true });
event_list.Items.Add(new { Type = "type", Description = "description" });

In WPF you are generally not supposed to set properties of the visual containers in the code-behind.

Upvotes: 3

Related Questions