Wpf 阻止网格中的控件更改其列宽
我不知道如何使用单元格中的用户控件正确管理网格列的宽度。我有一个用于窗口的xaml:Wpf 阻止网格中的控件更改其列宽,wpf,layout,grid,resize,Wpf,Layout,Grid,Resize,我不知道如何使用单元格中的用户控件正确管理网格列的宽度。我有一个用于窗口的xaml: <Grid> <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition Height="auto" /> <RowDefinition Height="*"/> </Grid.RowDefinitions
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Content="Button" Width="100" HorizontalAlignment="Left"/>
<TextBox Grid.Row="1" />
<local:UserControl1 Grid.Row="2"
HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>
用户控件是根据需要拉伸的图形集:
<UserControl x:Class="WpfApplication1.UserControl1"
Height="auto" Width="auto">
<Grid Background="Aqua">
<Path Fill="Coral" Stroke="Black" StrokeThickness="1"
Stretch="Uniform"
HorizontalAlignment="Left" VerticalAlignment="Top">
<Path.Data>
<RectangleGeometry Rect="40,20, 140,30" RadiusX="10" RadiusY="10" />
</Path.Data>
</Path>
</Grid>
</UserControl>
为了提供帮助,我将用户控件背景设置为蓝色
我希望列的宽度忽略用户控件的“自然”大小。我的意思是,我希望用户控件在列的布局期间不确定宽度,而是将其宽度调整为列的宽度
在本例中,最初网格会将列宽设置为按钮的值,用户控件会使用列宽来调整自身大小。然后,如果在文本框中输入了长文本,则一旦文本框开始比按钮宽,并且列也开始调整大小,用户控件就会进行调整,以保持与列相同的大小
我尝试了拉伸值的组合,并且在用户控件中使用了MeasureOverride()。后者不起作用,因为接收到的AvailableSize是无穷大的,而不是列宽。我可以通过给文本框一个名称,并将UserControl的宽度绑定到文本框的实际宽度,来实现(我相信)您想要的。以下是窗口网格的代码:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Content="Button" Width="100" HorizontalAlignment="Left"/>
<TextBox Grid.Row="1" x:Name="entryTextBox" />
<local:UserControl1 Grid.Row="2"
Width="{Binding ElementName=entryTextBox, Path=ActualWidth}"
HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>
希望有帮助 这是一个老问题,所以它可能不再对OP有帮助,但它可能会帮助其他人: 将UserControl1放在画布中。然后将宽度绑定到父栅格的实际宽度 例如:
<Grid Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Something Grid.Row="0"/>
<Canvas Grid.Row="1">
<MyControl Width="{Binding ActualWidth, ElementName=mainGrid, Mode=OneWay}"/>
</Canvas>
</Grid>
画布将采用可用宽度,但不会要求网格提供更多宽度。
画布内的控件无法从画布获取大小,因此必须手动为其指定大小。在这种情况下,我们希望给它一个父网格的大小。这很有帮助,谢谢,我将问题标记为已回答。在真实的上下文中,我不能使用文本框(或者它需要隐藏,但我不想这样做),因为列将包含多个控件,我将无法绑定到特定的。我读过其他关于绑定到gid ColumnDefinition的文章,但这并不成功,所以我仍在寻找这种可能性。