我对 WPF 很陌生。我经常发现自己在努力让一堆子控件组合宽度以匹配给定的父容器。如下所示:
<ListBox x:Name="BrugereListBox" Grid.Column="0" Grid.Row="3" DataContext="{DynamicResource Brugere}"
ItemsSource="{Binding}"
PreviewMouseLeftButtonDown="BrugereListBox_MouseLeftButtonDown"
PreviewMouseMove="BrugereListBox_PreviewMouseMove"
>
<ListBox.ItemTemplate >
<DataTemplate >
<Border BorderBrush="Black" BorderThickness="1" Margin="2">
<StackPanel Orientation="Vertical" IsEnabled="True"
PreviewMouseLeftButtonDown="StackPanel_PreviewMouseLeftButtonDown">
<StackPanel Orientation="Horizontal" >
<Label>Navn</Label>
<TextBox Text="{Binding Name}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Password</Label>
<TextBox Text="{Binding Password}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Email</Label>
<TextBox Text="{Binding Email}"></TextBox>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在这种情况下,我有兴趣获取堆栈面板的子项的宽度:
<StackPanel Orientation="Horizontal" >
<Label>Navn</Label>
<TextBox Text="{Binding Name}"></TextBox>
</StackPanel>
以匹配的宽度
<ListBox x:Name="BrugereListBox"
像这样的场景有什么通用的解决方案吗?
最佳答案
原来是一个骗局:
wpf border control to span the width of listboxItem
以及那里给出的答案:
This is probably more to do with the ListBoxItems themselves not taking up the full width of the ListBox. Add the HorizontalContentAlignment="Stretch" attribute to your ListBox and see if it stretches the individual items to fill the width.
所以改为:
<ListBox x:Name="BrugereListBox" Grid.Column="0" Grid.Row="3" DataContext="{DynamicResource Brugere}"
ItemsSource="{Binding}"
PreviewMouseLeftButtonDown="BrugereListBox_MouseLeftButtonDown"
PreviewMouseMove="BrugereListBox_PreviewMouseMove"
HorizontalContentAlignment="Stretch"
>
但正如 Kent 所说,在我看来,使用 Grid 会更好。
关于wpf - 子控件的宽度应与父容器的宽度匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2101582/