Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Set ListViewItem.Background With Binding

Tags:

c#

binding

wpf

I have a ListView in grid mode in which I display a list of data. The grid works, but I'm not able to bind the Background property. If "FileExists == false", then I want to display the line in red. Why is this not working?

The list gets loaded in Windows.Loaded. I also added the [ImplementPropertyChanged] attribute to the data class (using NuGet PropertyChanged.Fody) but that didn't help.

<ListView x:Name="VideosView" TabIndex="2" SelectedValuePath="VideoId" Margin="10,50,10,37" ButtonBase.Click="VideosView_ColumnHeaderClick">
    <ListView.Resources>
        <Style TargetType="{x:Type ListViewItem}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding FileExists}" Value="False">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Artist, Mode=OneWay}" Header="Artist" Width="100"/>
            <GridViewColumn DisplayMemberBinding="{Binding Title, Mode=OneWay}" Header="Title" Width="300"/>
            <GridViewColumn DisplayMemberBinding="{Binding Length, Converter={StaticResource TimeSpanConverter}, Mode=OneWay}" Header="Length" Width="40"/>
        </GridView>
    </ListView.View>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="Control.MouseDoubleClick" Handler="VideosView_ItemDoubleClick"/>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

Data class

[ImplementPropertyChanged]
public class VideoListItem {
    public VideoListItem() {
    }

    public int VideoId { get; set; }
    public string Artist { get; set; }
    public string Title { get; set; }
    public string FileName { get; set; }
    public int? Length { get; set; }
    public bool FileExists { get; set; }
    public bool IsInDatabase { get; set; }
}
like image 337
Etienne Charland Avatar asked Sep 30 '22 23:09

Etienne Charland


1 Answers

Your default ListViewItem Style in the ListView's Resources is not effective, because you explicitly set another ListViewItem Style by the ItemContainerStyle property.

Just drop the default style and move the DataTrigger to the ItemContainerStyle:

<ListView ...>
    ...
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="Control.MouseDoubleClick" Handler="VideosView_ItemDoubleClick"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding FileExists}" Value="False">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>
like image 157
Clemens Avatar answered Nov 15 '22 05:11

Clemens