更改GridView的一行背景

时间:2013-01-26 18:36:56

标签: c# wpf listview gridview background

我在WPF的GridView内有一个ListViewListView(和GridView列)有一个绑定ObservableCollection,用于填充它们。

如果给定GridView中的索引,如何更改ObservableCollection的一行背景?我需要以编程方式在C#中执行此操作。

<ListView Margin="12,39,0,0" Name="Library" DataContext="{Binding}" ItemsSource="{Binding _songData}" Height="681" VerticalAlignment="Top" MouseDoubleClick="Library_MouseDoubleClick"  ContextMenu="{StaticResource MyContextMenu}" AlternationCount="2" Background="AliceBlue" HorizontalAlignment="Left" Width="846">
        <ListView.View>
            <GridView x:Name="gvLibrary">
                <!--<GridViewColumn Width="20" Header="hi" DisplayMemberBinding="{Binding isSongPlaying}" x:Name="gvColumnPlaying" />-->
                <GridViewColumn Width="220" Header="Title" DisplayMemberBinding="{Binding Title}" x:Name="gvColumnTitle" />
                <GridViewColumn Width="180" Header="Artist" DisplayMemberBinding="{Binding Artist}" x:Name="gvColumnArtist" />
                <GridViewColumn Width="180" Header="Album" DisplayMemberBinding="{Binding Album}" x:Name="gvColumnAlbum" />
                <GridViewColumn Width="180" Header="Location" DisplayMemberBinding="{Binding Location}" x:Name="gvColumnLocation" />
                <GridViewColumn Width="80" Header="File Type" DisplayMemberBinding="{Binding Ext}" x:Name="gvColumnFileType" />
            </GridView>
        </ListView.View>
    </ListView>

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用StyleDataTrigger。首先在IsSelected

中包含的项目类上添加ListView属性
public class Song : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private bool _IsSelected;
    public bool IsSelected 
    {
        get { return _IsSelected; }
        set
        {
            _IsSelected = value;
            NotifyPropertyChanged("IsSelected");
        }
    }

    ...
}

然后将样式应用到ListViewItem s:

    <Style TargetType="{x:Type ListViewItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsSelected}" Value="True">
                <Setter Property="Background" Value="Red"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

现在,只要以编程方式设置IsSelected属性,相应的行就会突出显示:

_songData[5].IsSelected = true;