C# 在WPF中自定义GroupHeader
我正试图改变我的组标题的背景颜色,这取决于我给组标题后的值。我所有的datagrid行都有一个“Category”列,我在其中指定了不同的文本值,并且我希望根据不同的值为组标题提供不同的颜色 我的小组现在的照片: 我希望它是什么样子的图片:C# 在WPF中自定义GroupHeader,c#,wpf,xaml,grouping,wpfdatagrid,C#,Wpf,Xaml,Grouping,Wpfdatagrid,我正试图改变我的组标题的背景颜色,这取决于我给组标题后的值。我所有的datagrid行都有一个“Category”列,我在其中指定了不同的文本值,并且我希望根据不同的值为组标题提供不同的颜色 我的小组现在的照片: 我希望它是什么样子的图片: 我怎样才能做到这一点呢?你可以试着用border看看这些答案 将转换器应用于文本块的背景,以根据名称更改颜色。这对我有用: private void button1_Click(object sender, RoutedEventArgs e)
我怎样才能做到这一点呢?你可以试着用border
文本块的背景
,以根据名称更改颜色。这对我有用:
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;
}
private void按钮1\u单击(对象发送者,路由目标)
{
//检索保存GroupItems的stackpanel。
StackPanel sp=(StackPanel)getgenderantbytype(listView1,typeof(StackPanel));
//检索第二个GroupItem;
GroupItem gi=sp.Children[1]作为GroupItem;
//检索GroupItem内的扩展器;
Expander exp=(Expander)GetDescendantByType(gi,typeof(Expander));
//检索GroupItem内的扩展器;
Expander exp=(Expander)GetDescendantByType(gi,typeof(Expander));
System.Windows.Controls.Primitives.ToggleButton tb=(System.Windows.Controls.Primitives.ToggleButton)GetGenderantByType(exp,typeof(System.Windows.Controls.Primitives.ToggleButton));
Border br=(Border)getgenderantbytype(tb,typeof(Border));
//改变颜色;
br.Background=画笔。红色;
br.UpdateLayout();
}
公共静态可视GetDegenantByType(可视元素,类型)
{
if(element==null)返回null;
if(element.GetType()==type)返回元素;
Visual foundElement=null;
if(元素为FrameworkElement)
(元素作为FrameworkElement);
for(int i=0;i
资料来源: