WPF , Getting verticalstretch working as expected!

前端 未结 3 2305
醉话见心
醉话见心 2021-02-15 23:04

I am trying to make the vertical stretch to work as expected i WPF, but for some reason it only takes the space it needs, and not the space available.

First, I am using

相关标签:
3条回答
  • 2021-02-15 23:45

    I found a solution. I have to override the ItemsPanel Template to use a grid (or similar container):

    <ItemsControl>
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
          <Grid/>
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
    </ItemsControl>
    

    I have also in this case removed some of the xaml to make it more readble!

    Thanks

    0 讨论(0)
  • 2021-02-15 23:49

    The default for ItemsControl.ItemsPanelTemplate is StackPanel, which compresses all of its children vertically giving the symptoms you describe.

    The solution code-zoop gave changes this to <Grid>. This will work well as long as there is can only be one view in the region. But if the region has more than one view they will all be laid on top of each other instead of beside each other.

    If you want a region that can handle multiple views but allow views to stretch to the full size of the region, use a DockPanel instead:

    <ItemsControl>
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
          <DockPanel />
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
    </ItemsControl>
    

    This will put the first view in a panel on the left side, the next one beside it, and so on until the last view which will fill all the remaining space.

    If you prefer to have the multiple views stack vertically like they did with StackPanel, you'll have to set that up in ItemContainerStyle:

    <ItemsControl>
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
          <DockPanel />
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemContainerStyle>
        <Style>
          <Setter Property="DockPanel.Dock" Value="Top" />
        </Style>
      </ItemsControl.ItemContainerStyle>
    </ItemsControl>
    
    0 讨论(0)
  • 2021-02-15 23:52

    Have you tried setting HorizontalContentAlignment and VerticalContentAlignment to Stretch in the ItemsControl?

    0 讨论(0)
提交回复
热议问题