我无法弄清楚如何在其中一个单元格中使用用户控件正确管理网格列的宽度。我有一个窗口的xaml:
<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>
帮助我将用户控件背景设置为蓝色。
我希望列的宽度忽略用户控件的“自然”大小。我的意思是我希望用户控件在列布局期间不确定宽度,而是将其宽度调整为列的宽度。
在该示例中,最初Grid将列宽设置为按钮的值,用户控件将使用列宽调整自身大小。然后,如果在文本框中输入长文本,则只要文本框开始比按钮宽,并且列也开始调整大小,反过来用户控件将调整为保持与列相同的大小。
我尝试了拉伸值的组合,并且还在用户控件中使用了MeasureOverride()。后者不起作用,因为收到的AvalaibleSize是Infinity,而不是列宽。
答案 0 :(得分:7)
通过给TextBox命名,并将UserControl的宽度绑定到TextBox的ActualWidth,我能够实现您所寻找的(我相信)。这是Window网格的代码:
<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>
希望有所帮助!
答案 1 :(得分:3)
老问题,所以它可能不再对OP有所帮助,但它可能对其他人有所帮助:
将UserControl1放入Canvas中。然后将Width绑定到父Grid的ActualWidth。
示例:
<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>
画布将采用可用的宽度,但绝不会向Grid请求更多。 画布中的控件从Canvas中获取大小,因此您必须手动为其指定大小。在这种情况下,我们希望为它提供父Grid的大小。