How to make DockPanel fill available space

情到浓时终转凉″ 提交于 2019-11-29 02:51:15

问题


I'm trying the content of a shopping cart in an ItemsControl(ListBox). To do so, I've created the following DataTemplate:

<DataTemplate x:Key="Templates.ShoppingCartProduct"
              DataType="{x:Type viewModel:ProductViewModel}">
    <DockPanel HorizontalAlignment="Stretch">
        <TextBlock DockPanel.Dock="Left"
                   Text="{Binding Path=Name}"
                   FontSize="10"
                   Foreground="Black" />
        <TextBlock DockPanel.Dock="Right"
                   Text="{Binding Path=Price, StringFormat=\{0:C\}}"
                   FontSize="10"
                   Foreground="Black" />
    </DockPanel>
</DataTemplate>

When the items are displayed in my shopping cart however, the Name and Price TextBlocks are sitting right beside one another, and there is an extremely large amount of whitespace on the right hand side.

Was wondering what the best method to force the DockPanel to stretch to fill all the space made available by the ListItem was?


回答1:


Bind the Width of the DockPanel to the ActualWidth of the ListBoxItem:

<DockPanel Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}">
...

Another option: you could just redefine the ItemContainerStyle so that the ListBoxItem is stretched horizontally:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    </Style>
</ListBox.ItemContainerStyle>



回答2:


The nice thing about dock panels is they already fill all the available space. LastChildFill is true by default (but I set it below for clarity), so just don't set the DockPanel attribute on the last child, and it will fill the available space.

<DockPanel HorizontalAlignment="Stretch" LastChildFill="true">
    <TextBlock DockPanel.Dock="Left"
               Text="{Binding Path=Name}"
               FontSize="10"
               Foreground="Black" />
    <TextBlock 
               Text="{Binding Path=Price, StringFormat=\{0:C\}}"
               FontSize="10"
               Foreground="Black" />
</DockPanel>



回答3:


DockPanels are evil. Temptation to use StackPanel/DockPanel combination for complex layouts leads to "layout dead ends". Use a Grid:

<Grid>
  <TextBlock HorizontalAlignment="Left"
...
  <TextBlock HorizontalAlignment="Right"
...
/Grid>

I use Grids almost exclusively, using a separate grid for each block of elements that "belong together"



来源:https://stackoverflow.com/questions/1080479/how-to-make-dockpanel-fill-available-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!