gpt4 book ai didi

wpf - 在多个 WPF 控件之间共享列宽

转载 作者:行者123 更新时间:2023-12-02 13:25:43 25 4
gpt4 key购买 nike

有没有办法在控件之间共享列宽,而不仅仅是在同一控件上的多个网格之间共享列宽?

我想要得到的粗略图表:

alt text

我目前正在搞乱获取每个 UserControl 的第一列中标签的宽度,但这似乎是一个困惑的解决方案,CPU 负载很大(在渲染之前查找标签并计算文本的宽度是讨厌!)。

我一直在阅读尽可能多的有关 SharedSizeGroups 的内容,但没有任何迹象表明它们可以跨不同的控件工作。有没有一种简单的解决方案,甚至是一个不那么简单但又不那么可怕的解决方案?!

最佳答案

之前的两个答案都是正确的。下面是一个示例(主要取自 MSDN ),说明如何通过在父容器上设置 Grid.IsSharedSizeScope="True"来在两个不同的 UserControls 上使用此功能。请注意 ColumnDefinition 上的 SharedSizeGroup 属性。您可以通过切换 Grid.IsSharedSizeScope True/False 来查看效果

主窗口

<StackPanel Grid.IsSharedSizeScope="True">
<my:UserControl1 HorizontalAlignment="Left" x:Name="userControl11" />
<my:UserControl2 HorizontalAlignment="Left" x:Name="userControl21" />
</StackPanel>

用户控件1

<UserControl ...>
<Grid ShowGridLines="True" Margin="0,0,10,0">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="FirstColumn"/>
<ColumnDefinition SharedSizeGroup="SecondColumn"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" SharedSizeGroup="FirstRow"/>
</Grid.RowDefinitions>

<Rectangle Fill="Silver" Grid.Column="0" Grid.Row="0" Width="200" Height="100"/>
<Rectangle Fill="Blue" Grid.Column="1" Grid.Row="0" Width="150" Height="100"/>

<TextBlock Grid.Column="0" Grid.Row="0" FontWeight="Bold">First Column</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="0" FontWeight="Bold">Second Column</TextBlock>
</Grid>

</UserControl>

用户控件2

<UserControl ...>
<Grid ShowGridLines="True" Margin="0,0,10,0">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="FirstColumn"/>
<ColumnDefinition SharedSizeGroup="SecondColumn"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" SharedSizeGroup="FirstRow"/>
</Grid.RowDefinitions>

<Rectangle Fill="Silver" Grid.Column="0" Grid.Row="0" />
<Rectangle Fill="Blue" Grid.Column="1" Grid.Row="0" />

<TextBlock Grid.Column="0" Grid.Row="0" FontWeight="Bold">First Column</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="0" FontWeight="Bold">Second Column</TextBlock>
</Grid>
</UserControl>

关于wpf - 在多个 WPF 控件之间共享列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4501424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com