我有这段代码:
<GroupBox Style="{DynamicResource MaterialDesignCardGroupBox}" Grid.Row="0" Grid.Column="0" >
<Label Content="{Binding MatchController.Match.TeamHome}" />
<GroupBox.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Height="32" Width="32" Source="{Binding MatchController.Match.TeamHomeShield}" />
<Label Content="{Binding MatchController.Match.TeamHome}" />
<TextBlock Margin="8,0,0,0" VerticalAlignment="Center" Style="{StaticResource MaterialDesignSubheadingTextBlock}" Text="{Binding Match.TeamHome}"/>
</StackPanel>
</DataTemplate>
</GroupBox.HeaderTemplate>
</GroupBox>
正如您所看到的,我在GroupBox中有一个带有DataTemplate的标头模板。奇怪的是GroupBox外面的Label正确显示了TeamHome的值,但是在DataTemplate的StackPanel里面没有显示任何内容和绑定是一样的,为什么呢?生命之谜。
答案 0 :(得分:0)
您需要将GroupBox绑定到数据源,然后它才可用于模板。
<GroupBox Style="{DynamicResource MaterialDesignCardGroupBox}"
Grid.Row="0"
Grid.Column="0"
DataContext="{Binding MatchController}">
<Label Content="{Binding MatchController.Match.TeamHome}" />
<GroupBox.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Height="32"
Width="32"
Source="{Binding Match.TeamHomeShield}" />
<Label Content="{Binding Match.TeamHome}" />
<TextBlock Margin="8,0,0,0"
VerticalAlignment="Center"
Style="{StaticResource MaterialDesignSubheadingTextBlock}"
Text="{Binding Match.TeamHome}" />
</StackPanel>
</DataTemplate>
</GroupBox.HeaderTemplate>
</GroupBox>
答案 1 :(得分:0)
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Height="32" Width="32" Source="{Binding MatchController.Match.TeamHomeShield}" />
<Label Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.MatchController.Match.TeamHome}" />
<TextBlock Margin="8,0,0,0" VerticalAlignment="Center" Style="{StaticResource MaterialDesignSubheadingTextBlock}" Text="{Binding Match.TeamHome}"/>
</StackPanel>
</DataTemplate>
</GroupBox.HeaderTemplate>
如果在Window元素上设置了代码的DataContext,请使用此代码。否则,只需更改为具有此DataContext的最近元素的类型。