Mayfair
Mayfair

Reputation: 647

How to change a property of all listview items in WPF?

I am trying to change the BorderThickness property of all items in a ListView(WPF). The problem is that my listview's items are binding to properties of a List, where Song is a class. Here is how I bind them:

<ListView x:Name="listviewPlaylist" Margin="-4,-3,0,3" SelectionChanged="ListviewPlaylist_SelectionChanged" AllowDrop="True" Drop="ListviewPlaylist_Drop" DragEnter="ListviewPlaylist_DragEnter" PreviewMouseDown="ListviewPlaylist_PreviewMouseDown" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" MouseMove="ListviewPlaylist_MouseMove">
         <ListView.View>
                <GridView>
                    <GridViewColumn Header="Artist" Width="100" DisplayMemberBinding="{Binding Artist}" />
                    <GridViewColumn Header="Album" Width="200" DisplayMemberBinding="{Binding Album}" />
                    <GridViewColumn Header="Track no" Width="50" DisplayMemberBinding="{Binding TrackNo}" />
                    <GridViewColumn Header="Title" Width="200" DisplayMemberBinding="{Binding Title}" />
                    <GridViewColumn Header="Duration" Width="80" DisplayMemberBinding="{Binding Duration}" />
                 </GridView>
           </ListView.View>
</ListView>

If I now try to loop through listviewPlaylist.Items, I can't cast itemObj as a ListViewItem:

foreach (var itemObj in listviewPlaylist.Items)
            {
                var lvItem = (ListViewItem)itemObj; 
                lvItem.BorderThickness = new Thickness(1);
            }

I then get this error:

System.InvalidCastException: 'Unable to cast object of type 'MayPlayer.Song' to type 'System.Windows.Controls.ListViewItem'.'

Is there a way to access the items from the ListView instead of the class? I haven't found any solutions on the internet for this, I've also tried:

var lvItem = itemObj as ListViewItem; 

I'm not sure or there are more things that I have to add to this question, please let me know. Thanks in advance.

EDIT

Thanks to ASh, I used ItemContainerStyle:

Style style = new Style();
style.TargetType = typeof(ListViewItem);
style.Setters.Add(new Setter(ListViewItem.BorderThicknessProperty, new Thickness(1)));
listviewPlaylist.ItemContainerStyle = style;

Upvotes: 0

Views: 819

Answers (1)

ASh
ASh

Reputation: 35723

ListView generates ListViewItem for data items in ItemsSource, but those ListViewItems are not directly accessibly (and they are not supposed to really. When virtualization is enabled, one ListViewItem can be reused for multiple data items, when scrolling the ListView). Use ItemContainerStyle to change their properties:

<ListView>
  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
       <Setter Property="BorderThickness" Value="1"/>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>

Upvotes: 1

Related Questions