I am trying to add an image to my GroupBox Header like so:
<GroupBox>
<GroupBox.Header>
<StackPanel Orientation="Horizontal">
<Label Content="Test Box" />
<Image Source="MyImage.jpg" />
</StackPanel>
</GroupBox.Header>
.....
<!-- All my other code which I know works correctly -->
.....
<GroupBox>
However, what shows up for my GroupBox
Header
is:
I see this method of modifying the GroupBox
Header
all over the web when I search on how to do this but I cannot get it to work. I even tried removing the Image
in case that was causing an issue and it still give the same result.
What am I doing wrong here?
You can Try HeaderTemplate. Refer below code.
<GroupBox>
<GroupBox.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="Test Box" />
<Image Source="MyImage.jpg" />
</StackPanel>
</DataTemplate>
</GroupBox.HeaderTemplate>
</GroupBox>
I created a new WPF project using the default Visual Studio template, then inserted this in the XAML as the content of the Grid
element:
<GroupBox>
<GroupBox.Header>
<StackPanel Orientation="Horizontal">
<Label Content="Test Box" />
<Rectangle Fill="Orange" Width="50" Height="20" />
</StackPanel>
</GroupBox.Header>
</GroupBox>
It's using a Rectangle
instead of an image, but it worked fine for me.
The only thing I can think of is that something has changed the default GroupBox
template. Maybe try the XAML above in a new project and see if you can get that to work?
Which version of Windows are you using? I know the default templates differ slightly between Windows versions. The above was tested on Windows 7.
After reading Ganesh's post, I did a search for a GroupBox style and found that there was one in my project that I was unaware of. The GroupBox style was defined as follows:
<!-- GroupBox & GroupBox.Header Style -->
<Style x:Key="GroupBoxStyle" TargetType="{x:Type GroupBox}">
<Setter Property="Margin" Value="5" />
<Setter Property="Padding" Value="5" />
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding}" FontWeight="Bold"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type GroupBox}"
BasedOn="{StaticResource GroupBoxStyle}" />
By changing my code to the following I was able to override the default GroupBox style:
<GroupBox>
<GroupBox.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="Julius Caesar"/>
<Image Source="MyImage.jpg" />
</StackPanel>
</DataTemplate>
</GroupBox.HeaderTemplate>
......
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.