GroupBox.Header 不工作

GroupBox.Header not working

我正在尝试将图像添加到我的 GroupBox Header,如下所示:

<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>

但是,我的 GroupBox Header 显示的是:

当我搜索如何修改 GroupBox Header 时,我在整个网络上看到了这种修改方法,但我无法使用它。我什至尝试删除 Image 以防出现问题,但结果仍然相同。

我做错了什么?

您可以试试 HeaderTemplate。参考下面的代码。

<GroupBox>
            <GroupBox.HeaderTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="Test Box" />
                        <Image Source="MyImage.jpg" />
                    </StackPanel>
                </DataTemplate>                    
            </GroupBox.HeaderTemplate>
        </GroupBox>

我使用默认的 Visual Studio 模板创建了一个新的 WPF 项目,然后将其插入 XAML 作为 Grid 元素的内容:

<GroupBox>
    <GroupBox.Header>
        <StackPanel Orientation="Horizontal">
            <Label Content="Test Box" />
            <Rectangle Fill="Orange" Width="50" Height="20" />
        </StackPanel>
    </GroupBox.Header>
</GroupBox>

它使用 Rectangle 而不是图像,但对我来说效果很好。

我唯一能想到的是默认的 GroupBox 模板发生了变化。也许在新项目中尝试上面的 XAML,看看你是否可以让它工作?

您使用的 Windows 是哪个版本?我知道 Windows 版本之间的默认模板略有不同。以上是在 Windows 7.

上测试的

阅读 Ganesh 的 post 后,我搜索了一种 GroupBox 样式,发现我的项目中有一个我不知道的样式。 GroupBox 样式定义如下:

<!-- 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}" />

通过将我的代码更改为以下代码,我能够覆盖默认的 GroupBox 样式:

    <GroupBox>
        <GroupBox.HeaderTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Content="Julius Caesar"/>
                    <Image Source="MyImage.jpg" /> 
                </StackPanel>
            </DataTemplate>
        </GroupBox.HeaderTemplate>
        ......