【发布时间】:2023-04-02 19:55:01
【问题描述】:
我想在 MenuHeader 中将 Stackpanel 居中。 MenuItems 在整个菜单上均等地伸展。 我尝试将 Stackpanel Width 绑定到 Parent MenuItem Width,这在 Designer 中得到了完美的结果。但是,我在调试的时候,Stackpanel 还是靠左对齐的。
<Menu Grid.Column="1"
Grid.Row="1">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<MenuItem x:Name="OpenSourceView"
Background="{DynamicResource PrimaryHueMidBrush}"
HorizontalContentAlignment="Center"
Padding="0"
Click="OpenMenu"
Height="60"
>
<MenuItem.Header>
<StackPanel Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
>
<materialDesign:PackIcon
Kind="Camcorder"
Height="30"
Width="30"
Foreground="#262526"
HorizontalAlignment="Center"></materialDesign:PackIcon>
<AccessText Foreground="#262526"
FontWeight="Bold"
FontSize="12"
Width="Auto"
VerticalAlignment="Center"
HorizontalAlignment="Center">Source</AccessText>
</StackPanel>
</MenuItem.Header>
</MenuItem>
</Menu>
它在设计器中的外观以及我想要的效果:
https://i.imgur.com/2nkHxVw.png
调试时的样子:
https://i.imgur.com/ib1ILig.png
编辑: 我用网格替换了 Stackpanel。现在它居中但被截断了一半:
https://i.imgur.com/0piRPcM.png
<Menu Grid.Column="1"
Grid.Row="1">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<MenuItem x:Name="OpenSourceView"
Background="{DynamicResource PrimaryHueMidBrush}"
Padding="0"
Click="OpenMenu"
Height="60"
>
<MenuItem.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}}"/>
</Grid.ColumnDefinitions>
<materialDesign:PackIcon
Grid.Column="0"
Grid.Row="0"
Kind="Camcorder"
Height="30"
Width="30"
Foreground="#262526"
HorizontalAlignment="Center"/>
<AccessText Foreground="#262526"
Grid.Row="1"
FontWeight="Bold"
FontSize="12"
Width="Auto"
VerticalAlignment="Center"
HorizontalAlignment="Center">Source</AccessText>
</Grid>
</MenuItem.Header>
</MenuItem>
</Menu>
【问题讨论】:
-
StackPanel 是一个容器,其中所有子元素都放在堆栈中,也就是说一个接一个。我建议使用一列两行的网格。
-
@LPGTE.SOFTS 感谢您的回答。我试着听从你的建议,并用更新的代码编辑了我的问题。它仍然无法正常工作。