如何动态更改 WPF 列表视图行背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42280225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:01:00  来源:igfitidea点击:

How to change WPF listview row background colour dynamically?

wpf

提问by PKB85

I am new to WPF, I have the following xaml code for list view:

我是 WPF 的新手,我有以下用于列表视图的 xaml 代码:

<ListView x:Name="listView1" ItemsSource="{Binding Processes1}"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="470" Margin="10,95,150,6" Width="565" SelectionChanged="NetscalerCfgView_listView1_SelectionChanged">
   <ListView.View>
       <GridView>
           <GridViewColumn Header="Line"  DisplayMemberBinding="{Binding srcCfgLineNum}"/>
           <GridViewColumn Header="Source Config" DisplayMemberBinding="{Binding srcConfigText}"/>
       </GridView>
   </ListView.View>
</ListView>

I have the class SrcListViewInfo which I am displaying in listview:

我有我在列表视图中显示的类 SrcListViewInfo:

public class SrcListViewInfo
{
    public int srcCfgLineNum { get; set; }
    public string srcConfigText { get; set; }
}

I have declared it in windows load event like this:

我已经在 Windows 加载事件中声明了它,如下所示:

public ObservableCollection<SrcListViewInfo> processes1 = null;
processes1 = new ObservableCollection<SrcListViewInfo>();

I want to color the row background dynamically in a different function under different cases dynamically, for example:

我想在不同的情况下在不同的函数中动态地为行背景着色,例如:

case DiffResultSpanStatus.DeleteSource:
    for (i = 0; i < drs.Length; i++)
    {
        SrcListViewInfo newInfo = new SrcListViewInfo();
        newInfo.BackgroundColor = new SolidColorBrush(Colors.Red);
        // newInfo.BackgroundColor = Brushes.Red;
        newInfo.srcCfgLineNum = cnt;
        newInfo.srcConfigText = ((TextLine)source.GetByIndex(drs.SourceIndex + i)).Line;
        // newInfo.BackgroundColor = Brushes.Red; << want to set the color like this.

I have tried solid brush but it does not seem to be working correctly.

我试过固体刷,但它似乎不能正常工作。

回答by Saud Khan

You can Style the ListViewItem in xaml directly,

您可以直接在 xaml 中为 ListViewItem 设置样式,

Example:

例子:

Assuming your "Name" variable is a string, you can try

假设您的“名称”变量是一个字符串,您可以尝试

<ListView Name="whatever">
  <ListView.Resources>
    <Style TargetType="{x:Type ListViewItem}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Name}"
                      Value="John">
          <Setter Property="Background"
                  Value="Red" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListView.Resources>
....

Now any ListView Row with "Name" Value of "John" will have a "Red" Background

现在,“名称”值为“John”的任何 ListView 行都将具有“红色”背景

回答by Ron

an option

一个选项

is to use IMultiValueConverterin ListView.ItemTemplate

是用IMultiValueConverterListView.ItemTemplate

<ListView DataContext="{Binding}" ItemsSource="{Binding Models}" AlternationCount="3" >
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name  }"/>
                    <TextBlock Text="{Binding Desc }"/>
                    <StackPanel.Background> 
                            <MultiBinding Converter="{StaticResource BackConverter}">
                                <Binding />
                                <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}"/>
                            </MultiBinding> 
                    </StackPanel.Background>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>


public class BackConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // write your logic (You have the model and the view model)

        var index = ((ItemsControl)values[1]).Items.IndexOf(values[0]);
        if (index % 2 == 0)
            return Brushes.Gray;
        return Brushes.White;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

another option

另外一个选项

is to use ItemsControl.AlternationIndexin ListView.ItemContainerStyle

是用ItemsControl.AlternationIndexListView.ItemContainerStyle

<ListView DataContext="{Binding}" ItemsSource="{Binding Models}" AlternationCount="3" >
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Style.Triggers>
                    <Trigger Property="ItemsControl.AlternationIndex"  Value="0">
                        <Setter Property="Background" Value="Red" />
                    </Trigger>
                    <Trigger Property="ItemsControl.AlternationIndex"  Value="1">
                        <Setter Property="Background" Value="Green" />
                    </Trigger>
                    <Trigger Property="ItemsControl.AlternationIndex"  Value="2">
                        <Setter Property="Background" Value="Blue" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>

Edit

编辑

public MainWindow()
{
     InitializeComponent();
     lv.ItemsSource = new List<string> { "a", "b", "c", "d", "e" };
}

回答by CoRe23

After some googling i found out my own solution I am using Listview.ItemsSource and as source i use List with ListViewItems Then i can set background of specify ListViewItem in List, and just refresh listview.

经过一番谷歌搜索后,我找到了自己的解决方案,我使用的是 Listview.ItemsSource,作为源,我使用 List 和 ListViewItems 然后我可以在 List 中设置指定 ListViewItem 的背景,然后刷新列表视图。

XAML:

XAML:

 <ListView x:Name="listView" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" Grid.Row="1">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="IP"  DisplayMemberBinding="{Binding IP}" Width="Auto"/>
                        <GridViewColumn Header="PING" DisplayMemberBinding="{Binding Ping}" Width="Auto"/>
                        <GridViewColumn Header="Host Name" DisplayMemberBinding="{Binding DNS}" Width="Auto"/>
                        <GridViewColumn Header="Mac" DisplayMemberBinding="{Binding MAC}" Width="Auto"/>
                        <GridViewColumn Header="Vyrobce" DisplayMemberBinding="{Binding Manufacturer}" Width="Auto"/>
                    </GridView>
                </ListView.View>
            </ListView>

Fill ListView with Items with Gray Background:

用灰色背景的项目填充 ListView:

List<ListViewItem> ITEMS = new List<ListViewItem>();
private void button_Click(object sender, RoutedEventArgs e)
{
    for (int i = 1; i < 20; i++)
    {
        ListViewItem OneItem = new ListViewItem();
        OneItem.Background = Brushes.LightGray;
        OneItem.Content = new Device() { IP = "1.1.1.1", Ping = "30ms", DNS = "XYZ", MAC = "2F:3C:5F:41:F9", Manufacturer = "Intel" };
        ITEMS.Add(OneItem);
        listView.ItemsSource = ITEMS;
    }
    listView.Items.Refresh();
}
public class Device
{
    public string IP { get; set; }
    public string Ping { get; set; }
    public string DNS { get; set; }
    public string MAC { get; set; }
    public string Manufacturer { get; set; }
}

Create Method for Row Change Color:

创建行更改颜色的方法:

private void ChangeRowColor(int RowIndex,SolidColorBrush NewBackground)
{
    ITEMS[RowIndex].Background = NewBackground;
    listView.Items.Refresh();
}

And use it:

并使用它:

private void button1_Click(object sender, RoutedEventArgs e)
{
    ChangeRowColor(4, Brushes.Green);
}