2016-08-09 23 views
1

足够让我的头撞在我的键盘上。我有一个完美的作品像这样的列表视图:在代码背后创建并设计一个ListView全部在

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

Unstyled listview

现在我想要做的就是让这些组头大胆。 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除非我重新绑定它(这似乎是多余的,正确或者不工作)。有没有更简单的样式组头开(或,一样好,风格其它列表视图组标题下的项目)

回答

0

事实上,这是没有使用这么好的一个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); 

我希望它可以帮助你。

相关问题