wpf - 子控件的宽度应与父容器的宽度匹配

标签 wpf controls width parent

我对 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/

相关文章:

jquery - 如何制作像本站那样的背景图片?

css - 宽度为 : 100% inside position: absolute on IE7 的表格

excel - 控件的 VBA 集合(数组?)

delphi - 如何在其自身事件中释放控件?

c# - 如何处理 Form 上的大量控件?

css - 使用 em 作为宽度和高度的测量单位进行 flex 设计

c# - 风格完全改变

c# - 以编程方式访问 WPF 控件

wpf - 将组合框 SelectedValue 绑定(bind)到文本框

c# - 区分x :Name and Name in Wpf application