在WPF中自定义组头

时间:2016-12-28 02:23:59

标签: c# wpf xaml grouping wpfdatagrid

我试图根据我给他们分组的值来改变我的组头的背景颜色。我的所有数据网格行都有一个"类别"我分配不同文本值的列,我想根据不同的值为组头提供不同的颜色。

我的团队现在的照片: http://imgur.com/a/JDlAQ

我想要它的图片: http://imgur.com/a/qdpxW

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

哟可以尝试用边框<边框背景=“黑色”>

答案 1 :(得分:0)

请参阅这些答案,WPF How to set DataGrid.Group header text when it's actually collapsed

How do I get the value of a cell in a grouped CollectionView?

将转换器应用到Background的{​​{1}},根据名称更改颜色。

答案 2 :(得分:0)

这对我有用:

private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Retrieve the stackpanel that holds the GroupItems.
            StackPanel sp = (StackPanel)GetDescendantByType(listView1, typeof(StackPanel));

            //Retrieve the sencond GroupItem;
            GroupItem gi = sp.Children[1] as GroupItem;

            //Retrieve the Expander inside the GroupItem;
            Expander exp = (Expander)GetDescendantByType(gi, typeof(Expander));

            //Retrieve the Expander inside the GroupItem;
            Expander exp = (Expander)GetDescendantByType(gi, typeof(Expander));

            System.Windows.Controls.Primitives.ToggleButton tb = (System.Windows.Controls.Primitives.ToggleButton)GetDescendantByType(exp, typeof(System.Windows.Controls.Primitives.ToggleButton));

            Border br = (Border)GetDescendantByType(tb, typeof(Border));

            //Change color;
            br.Background = Brushes.Red;
            br.UpdateLayout();
        }

        public static Visual GetDescendantByType(Visual element, Type type)
        {
            if (element == null) return null;
            if (element.GetType() == type) return element;
            Visual foundElement = null;
            if (element is FrameworkElement)
                (element as FrameworkElement).ApplyTemplate();
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
                foundElement = GetDescendantByType(visual, type);
                if (foundElement != null)
                    break;
            }
            return foundElement;
        }

来源:How to access group items of a listview in code-behind?