C# 当ColumnDefinitions';宽度是动态的?
这是一个WPF窗口,其中包含一个C# 当ColumnDefinitions';宽度是动态的?,c#,.net,wpf,grid-layout,C#,.net,Wpf,Grid Layout,这是一个WPF窗口,其中包含一个UserControl。UserControl是一个简单的网格,有两列,没有确定的宽度。在第一列中,我添加了一个简单的TextBox,设置为水平拉伸。第二列为空 当我缩小窗口的宽度时,WPF会裁剪我的UserControl,尽管它的右侧仍然有一个巨大的空白!看起来它试图让我的第二列与我的第一列一样大小,即使它是空的,但奇怪的是,这发生在我的USER控件之外(否则空白空间将是粉色的)!p> 主窗口.XAML: <Window x:Class="WPF_Grid
UserControl
。UserControl
是一个简单的网格
,有两列,没有确定的宽度。在第一列中,我添加了一个简单的TextBox
,设置为水平拉伸。第二列为空
当我缩小窗口的宽度时,WPF会裁剪我的UserControl
,尽管它的右侧仍然有一个巨大的空白!看起来它试图让我的第二列与我的第一列一样大小,即使它是空的,但奇怪的是,这发生在我的USER控件之外(否则空白空间将是粉色的)!p>
主窗口.XAML:
<Window x:Class="WPF_Grid_Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF_Grid_Test"
Title="MainWindow" Height="350" Width="525">
<local:TestUserControl HorizontalAlignment="Left"/>
</Window>
我试图实现的行为是,当我缩小窗口时,UserControl
保留其DesiredSize
。但是只有当窗口没有空格时,UserControl
才应该接受“收缩”处理
尝试从ColumnDefinitions中删除
Width=Auto
,您应该可以看到在容器缺少空间之前,最右边的元素是如何调整大小的。这就是为什么我认为这确实是一个WPF布局错误。您应该明确指定列的宽度
例如,如果希望两列的大小始终相同,请使用Width=“*”
如果您希望两列都尽可能宽,请使用
Width=“Auto”
。这将导致不同大小的列。如果希望一列尽可能宽,另一列使用剩余的空间,请在第一列上使用
Width=“Auto”
,在第二列上使用Width=“*”
。设置这些选项将根据用户控件的内容为其提供固定的宽度,这不是我要寻找的行为。我同意UserControl在缺少空间时调整自身大小并裁剪其元素。如果你尝试上面的代码,你会注意到UserControl被压缩了,即使容器有足够的空间来显示它。我已经用你的想法更新了我的初始帖子,并解释了它如何不能提供预期的行为。
<UserControl x:Class="WPF_Grid_Test.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Pink" Height="100">
<Grid Margin="0" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox Text="Why is WPF cropping me even though there's a huge blank space to eat into?" VerticalAlignment="Center" />
</Grid>
</UserControl>
<UserControl x:Class="WPF_Grid_Test.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Pink" Height="100">
<Grid Margin="0" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Text="Resize us" VerticalAlignment="Center" Grid.Column="0" />
<TextBox Text="only when" VerticalAlignment="Center" Grid.Column="1" />
<TextBox Text="you're out of space!" VerticalAlignment="Center" Grid.Column="2" />
</Grid>
</UserControl>