我正在 WPF 中創建一個表單。該表單的左側有帶有 TextBlock 的 TextBox。下面是帶有 GridLines 的螢屏截圖:

我希望它看起來像這樣(原諒 MS Paint 風格):

問題是:除非我將 Horizo??ntalAlignment 設定為 Stretch,否則文本框非常小,但如果我這樣做,我無法將它們對齊到左側。如何讓包含 TextBlock/TextBox 的 Grid 向左對齊并使TextBox 填充所有可用空間?
如果我對寬度進行硬編碼,這很容易,但這顯然不適用于調整大小。我嘗試過使用 Stack 和 Dock Panels 來固定網格,但沒有運氣。
I can't use 
您當前的代碼存在一些問題。首先,使用 DockPanel 來托管 TextBlock/TextBox 對,其次,沒有控制元件設定 Grid.IsSharedSizeScope=true。您還為文本框列定義了共享大小,而實際上您只是希望它占用所有可用空間。
這是一些實作所需布局的代碼:
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--Left hand side content goes here-->
<StackPanel Orientation="Vertical" Grid.Column="1"
Grid.RowSpan="2"
Margin="20,0,0,0"
Grid.IsSharedSizeScope="True" >
<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="Grid.Column" Value="0"/>
<Setter Property="Text" Value="Input Name:"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</StackPanel.Resources>
<Border BorderBrush="Blue" BorderThickness="5">
<Grid ShowGridLines="True" HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="TextBlockColumn"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock/>
<TextBox Grid.Column="1"
VerticalAlignment="Center"
Style="{StaticResource FormTextBox}"
Margin="5,0,5,0"/>
</Grid>
</Border>
<Border BorderBrush="Red" BorderThickness="5">
<Grid ShowGridLines="True" HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="TextBlockColumn"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock/>
<TextBox Grid.Column="1"
VerticalAlignment="Center"
Style="{StaticResource FormTextBox}"
Margin="5,0,5,0"/>
</Grid>
</Border>
</StackPanel>
</Grid>
此代碼產生:

In reality though, if you're going for maximum usability, you'll want to create your own control for the TextBlock/TextBox, and then you could just put it in an ItemsControl of some kind for dynamic content.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450814.html
