在后面的代码中创建并设置ListView样式

时间:2016-08-09 02:56:10

标签: c# wpf listview

在键盘上敲我的头。我有一个像这样完美的列表视图:

FCView.FCListView.ItemsSource = myItemsSouce;
CollectionView view = CollectionViewSource.GetDefaultView(FCView.FCListView.ItemsSource) as CollectionView;
PropertyGroupDescription gd = new PropertyGroupDescription("Root");
view.GroupDescriptions.Add(gd);

现在,我想做的就是将这些组标题加粗。 3个小时后,这是我能想到的最好的:

Style myStyle = new Style(typeof(GroupItem));    
DataTemplate dt = new DataTemplate();
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(GroupItem));
spFactory.SetValue(GroupItem.FontWeightProperty, FontWeights.Bold);
spFactory.SetValue(GroupItem.ForegroundProperty, new SolidColorBrush(Colors.Red));
dt.VisualTree = spFactory;
GroupStyle groupStyle = new GroupStyle();
groupStyle.HeaderTemplate = dt;
groupStyle.ContainerStyle = myStyle;
FCListView.GroupStyle.Add(groupStyle);

但这会覆盖我的GroupDescription,除非我重新绑定它(这似乎是多余的,也不能正常工作)。是否有一种更简单的方式来设置组标题的样式(或者,同样好的,样式组头标题下的其他列表视图项目)

1 个答案:

答案 0 :(得分:1)

确实使用GroupItemContentControl)来对数据进行数据处理是不太好的。在你的位置我会使用一个简单的TextBlock

关键是您无法看到群组说明,因为您的DataTemplate没有与他们绑定。所以只需添加注释行:

Style myStyle = new Style(typeof(GroupItem));    
DataTemplate dt = new DataTemplate();
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(GroupItem));
spFactory.SetValue(GroupItem.FontWeightProperty, FontWeights.Bold);
spFactory.SetValue(GroupItem.ForegroundProperty, new SolidColorBrush(Colors.Red));
// You missed next line
spFactory.SetBinding(GroupItem.ContentProperty, new Binding("Name"));
//
dt.VisualTree = spFactory;
GroupStyle groupStyle = new GroupStyle();
groupStyle.HeaderTemplate = dt;
groupStyle.ContainerStyle = myStyle;
FCListView.GroupStyle.Add(groupStyle);

通过这种方式,您可以将群组的Name(即其说明)与GroupItem的内容绑定。

创建模板的最佳方法是使用XAML。无论如何,如果出于某些原因我应该使用代码,我将使用:

DataTemplate dt = new DataTemplate();
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(TextBlock));
spFactory.SetValue(TextBlock.FontWeightProperty, FontWeights.Bold);
spFactory.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.Red));
spFactory.SetBinding(TextBlock.TextProperty, new Binding("Name"));
dt.VisualTree = spFactory;
GroupStyle groupStyle = new GroupStyle();
groupStyle.HeaderTemplate = dt;

FCListView.GroupStyle.Add(groupStyle);

我希望它可以帮到你。