改变 ListView 中各行的背景色
后台代码:
public class ListViewItemStyleSelector : StyleSelector
{
public override Style SelectStyle(object item,
DependencyObject container)
{
Style st = new Style();
st.TargetType = typeof(ListViewItem);
Setter backGroundSetter = new Setter();
backGroundSetter.Property = ListViewItem.BackgroundProperty;
ListView listView =
ItemsControl.ItemsControlFromItemContainer(container)
as ListView;
int index =
listView.ItemContainerGenerator.IndexFromContainer(container);
if (index % 2 == 0)
{
backGroundSetter.Value = Brushes.LightBlue;
}
else
{
backGroundSetter.Value = Brushes.Beige;
}
st.Setters.Add(backGroundSetter);
return st;
}
}
下面的示例演示如何为 StyleSelector 定义 ResourceKey。namespc 前缀映射到 CLR 命名空间和其中定义了 StyleSelector 的对应程序集。有关更多信息,请参见 XAML 命名空间和命名空间映射。
<namespc:ListViewItemStyleSelector x:Key="myStyleSelector"/>
下面的示例演示如何将 ListView 的 ItemContainerStyleSelector 属性设置为此 StyleSelector 资源。
<ListView
ItemsSource="{Binding Source={StaticResource EmployeeData},
XPath=Employee}"
ItemContainerStyleSelector="{DynamicResource myStyleSelector}" >
<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>
这是方法,但是<namespc:ListViewItemStyleSelector x:Key="myStyleSelector"/>这段代码,不知道它是什么意思,具体代表什么,希望得到高手的指点,并且指定它所写的位置!!
谢谢谢。。。。。。
[解决办法]
WPF中的应用!!
[解决办法]
该回复于2010-03-27 14:53:15被版主删除
[解决办法]
我已解决:它是双重应用
//引入
xmlns:namespc="clr-namespace:ListViewItemStyleSelector;assembly=ListViewItemStyleSelector"
//然后在资源里
<Window.Resources>
<namespc:ListViewItemStyleSelector x:Key="myStyleSelector"/>
</Window.Resources>
问题解决,可以成功!
[解决办法]
ListView listView = ItemsControl.ItemsControlFromItemContainer(container) as ListView;
ListView listView;
listView.Items.Add(container as ListViewItem);