WPF Square auto-size to parent container

笑着哭i 提交于 2019-12-13 01:25:09

问题


I have a UniformGrid object in my WPF project that has 2 rows and 3 cols and its width and height are set to auto (with both alignments set to Stretch).

This grid will hold 6 squares that I want to fill as much of their cell as possible and be centered horizontally and vertically.

What do I need to be added to allow for the squares to increase/decrease their length/width based on the dynamic size of the parent? I.E., when the window is resized.

Here is my xaml so far:

    <UniformGrid Rows="2" Columns="3">
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
        <Rectangle Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100"/>
    </UniformGrid>

Edit:

And the Rectangle objects need to remain square.


回答1:


<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
  <Grid>
<UniformGrid Rows="2" Columns="3">
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
<Viewbox Stretch="Uniform"><Rectangle Height="100" Width="100" Fill="#FFF4F4F5" Stroke="Black" /></Viewbox>
    </UniformGrid>
  </Grid>
</Page>



回答2:


You could do this:

<UniformGrid.Resources>
    <Style TargetType="Rectangle">
        <Setter Property="Width"
                Value="{Binding RelativeSource={RelativeSource Mode=Self},Path=ActualHeight}" />
    </Style>
</UniformGrid.Resources>

Or you could bind the Height to the ActualWidth.

Unfortunately this will not keep them stretched to the maximum.




回答3:


If you remove the height and width properties it will do just that.



来源:https://stackoverflow.com/questions/8682345/wpf-square-auto-size-to-parent-container

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