列自动网格中的列表框超过wpf中的父宽度

时间:2016-03-31 09:11:56

标签: c# wpf xaml scroll listbox

我们说我有以下xaml:

<Grid MaxHeight="200" d:LayoutOverrides="Width">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <ListBox Height="170" ScrollViewer.HorizontalScrollBarVisibility="Visible" ItemsSource="{Binding DataModel.LocalData.ListFabricRules}" IsEnabled="{Binding DataModel.LocalData.Enabled}" SelectedItem="{Binding DataModel.LocalData.ListFabricRulesSelected}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <TextBlock Text="{Binding Descript}" />
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <StackPanel Grid.Column="1" Orientation="Vertical" d:LayoutOverrides="Height" Margin="10,0" IsEnabled="{Binding DataModel.LocalData.EnabledRules}">
        <Button Content="Test" />
    </StackPanel>
</Grid>

布局的目标是列表框填充可用空间(在列中),在列表框的右侧有一个按钮。 问题如下:当列表框显示水平滚动时(因为包含文本很大),它们的宽度增量会改变网格比例,因此按钮向右移动,不考虑边距并占用超过主网格。将主网格放入Scrollviewer时,滚动部分隐藏。主网格的主机是usercontrol。

Click here you can see the image where is the listbox without horizontal scroll. You can the scroll of scrollviewer.In this capture no problem

In this image there are large items (horizontally), so the horizontal scroll in listbox is visible. In this case, the scroll of scrollviewer is partially hide. It's because the listbox has more width. I don't know why

1 个答案:

答案 0 :(得分:1)

问题在于,您没有将列表框的宽度定义为&#39; auto在两列中都是&#39;。 要解决这个问题,你必须使用*或使用来设置宽度的百分比 最大或最小宽度。

<Grid MaxHeight="200" d:LayoutOverrides="Width">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="80*"/>
    <ColumnDefinition Width="20*"/>
</Grid.ColumnDefinitions>
<ListBox Height="170" ScrollViewer.HorizontalScrollBarVisibility="Visible" ItemsSource="{Binding DataModel.LocalData.ListFabricRules}" IsEnabled="{Binding DataModel.LocalData.Enabled}" SelectedItem="{Binding DataModel.LocalData.ListFabricRulesSelected}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock Text="{Binding Descript}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Column="1" Orientation="Vertical" d:LayoutOverrides="Height" Margin="10,0" IsEnabled="{Binding DataModel.LocalData.EnabledRules}">
    <Button Content="Test" />
</StackPanel>