当前位置:   article > 正文

WPF开发中遇到的问题及解决系列(三):如何改变ListView 中各行的背景色(背景色产生交替效果)...

wpf 设置listview奇偶行变色

方法 1:定义使用 IValueConverter 来使背景色产生交替效果的样式
下面的示例显示如何为将 Background 属性的值绑定到 IValueConverterListViewItem 控件定义 Style

< Style  x:Key ="myItemStyle"  TargetType =" {x:Type ListViewItem} " >
  
< Setter  Property ="Background" >
    
< Setter.Value >
      
< Binding  RelativeSource =" {RelativeSource Self} "  
               Converter
=" {StaticResource myConverter} " />
    
</ Setter.Value >
  
</ Setter >
</ Style >

下面的示例为 IValueConverter 定义 ResourceKey。下面的示例为 IValueConverter 定义 ResourceKey
< namespc:BackgroundConverter  x:Key ="myConverter" />

下面的示例显示依据行索引设置 Background 属性的 IValueConverter 的定义。下面的示例显示依据行索引设置 Background 属性的 IValueConverter 的定义。
public   sealed   class  BackgroundConverter : IValueConverter
{
    
public object Convert(object value, Type targetType, object parameter, 
        CultureInfo culture)
    
{
        ListViewItem item 
= (ListViewItem)value;
        ListView listView 
= 
            ItemsControl.ItemsControlFromItemContainer(item) 
as ListView;
        
// Get the index of a ListViewItem
        int index = 
            listView.ItemContainerGenerator.IndexFromContainer(item);

        
if (index % 2 == 0)
        
{
            
return Brushes.LightBlue;
        }

        
else
        
{
            
return Brushes.Beige;
        }

    }

下面的示例演示如何定义使用 Style 作为其 ItemContainerStyle 以便提供所需布局的 ListView。下面的示例演示如何定义使用 Style 作为其 ItemContainerStyle 以便提供所需布局的 ListView
< ListView  Name ="theListView"  
          ItemsSource
=" {Binding Source={StaticResource EmployeeData}, 
                                        XPath=Employee}
"
          ItemContainerStyle
=" {StaticResource myItemStyle} "   >
  
< ListView.View >
    
< GridView >
      
< GridViewColumn  DisplayMemberBinding =" {Binding XPath=FirstName} "  
                      Header
="First Name"  Width ="120" />
      
< GridViewColumn  DisplayMemberBinding =" {Binding XPath=LastName} "  
                      Header
="Last Name"  Width ="120" />
      
< GridViewColumn  DisplayMemberBinding =" {Binding XPath=FavoriteCity} "  
                      Header
="Favorite City"  Width ="120" />
    
</ GridView >
  
</ ListView.View >
</ ListView >

另2种方法详见msdn: http://msdn2.microsoft.com/zh-cn/library/ms750769.aspx

转载于:https://www.cnblogs.com/yingql/archive/2008/03/24/1120352.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/537669?site
推荐阅读
相关标签