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

本文关键字:设置 ListView 样式 创建 代码 在后面 | 更新日期: 2023-09-27 18:01:36

我受够了埋头敲键盘。我有一个像这样完美工作的列表视图:

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,除非我重新绑定它(这似乎是多余的,也不能正常工作)。是否有一种更简单的方法来样式组标题(或者,同样好,样式组标题下的其他listview项)

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

事实上,使用GroupItem(这是一个ContentControl)的数据传递你的头是不那么好。在你的位置,我会使用一个简单的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);

我希望它能帮助你。