WPF使用绑定设置ListViewItem.Background

时间:2014-09-01 20:34:50

标签: c# wpf binding

我在网格模式下有一个ListView,我在其中显示数据列表。网格有效,但我无法绑定Background属性。如果“FileExists == false”,那么我想以红色显示该行。为什么这不起作用?

列表在Windows.Loaded中加载。我还将[ImplementPropertyChanged]属性添加到数据类(使用NuGet PropertyChanged.Fody),但这没有帮助。

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

数据类

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

1 个答案:

答案 0 :(得分:2)

ListView的资源中的默认ListViewItem样式无效,因为您通过ItemContainerStyle属性显式设置另一个 ListViewItem样式。

只需删除默认样式并将DataTrigger移动到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>