2

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

像这样的场景有什么通用的解决方案吗?

4

2 回答 2

6

原来是一个骗局:

wpf边框控件跨越listboxItem的宽度

以及那里给出的答案:

这可能更多地与 ListBoxItems 本身没有占用 ListBox 的整个宽度有关。将 Horizo​​ntalContentAlignment="Stretch" 属性添加到您的 ListBox 并查看它是否会拉伸各个项目以填充宽度。

所以改为:

<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 会更好。

于 2010-01-20T13:37:26.770 回答
5

使用正确的面板,你会没事的。StackPanel根据它的方向和它的孩子,它自己决定它的宽度/高度。使用 a Grid,它只会占用它给定的空间 - 不多也不少。

于 2010-01-20T13:31:04.790 回答