问题
I have a StackPanel
with a fixed width. Inside that StackPanel
I have a GridView
, which Width
should be limited to its parent width (smth like Width="*").
My sample XAML:
<StackPanel Orientation="Horizontal" Width="300" Height="300">
<TextBox Width="50" Margin="0" Height="50" Background="Blue"></TextBox>
<GridView >
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid Orientation="Horizontal" FlowDirection="LeftToRight" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.Items>
<TextBox Width="50" Margin="0" Height="50" Background="Green"></TextBox>
<TextBox Width="50" Margin="0" Height="50" Background="Green"></TextBox>
<TextBox Width="50" Margin="0" Height="50" Background="Green"></TextBox>
<TextBox Width="50" Margin="0" Height="50" Background="Green"></TextBox>
<TextBox Width="50" Margin="0" Height="50" Background="Green"></TextBox>
</GridView.Items>
</GridView>
</StackPanel>
In this example the GridView
width is wider than the parent, so some of its items are not displayed (not wrapped). When I set GridView
width to a fixed value items are wrapped, but I can't use fixed value in my project.
回答1:
In this scenario it's more beneficial to have a Grid
rather than a StackPanel
. The code below will achieve the desired effect (the GridView
will take up any unused space next to the TextBox
).
<Grid Width="300" Height="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Height="50" Background="Blue"></TextBox>
<GridView Grid.Column="1">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid Orientation="Horizontal" FlowDirection="LeftToRight" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.Items>
<TextBox Width="50" Margin="0" Height="50" Background="Green"/>
<TextBox Width="50" Margin="0" Height="50" Background="Green"/>
<TextBox Width="50" Margin="0" Height="50" Background="Green"/>
<TextBox Width="50" Margin="0" Height="50" Background="Green"/>
<TextBox Width="50" Margin="0" Height="50" Background="Green"/>
</GridView.Items>
</GridView>
</Grid>
回答2:
You can try horizontalscrollmode enabled and horizontalscrollbarvisibility to true. But data would not be wrapped.
来源:https://stackoverflow.com/questions/16438661/gridview-width-inherited-from-parent