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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值