【发布时间】:2018-08-07 13:29:51
【问题描述】:
我正在制作各种图片库,目前正在通过 C# 将图片动态加载到网格中。如果我不应该使用网格来显示图像,我非常愿意将其更改为更适合的控件,但它需要对窗口大小调整友好。
当我调整窗口大小时,我希望发生以下事情:
- 所有图像都保持完全相同的大小。它们已经适合网格槽,同时保持其纵横比
- 网格空间本身也没有调整大小
- 网格包含更多或更少的行/列,具体取决于窗口可以容纳多少行/列。
这意味着,如果将窗口的大小调整为非常薄且非常高,则网格将包含一列(或两列,或者需要多少列)和许多行来显示图像。
如果它很宽,但又不高,那么它只会有一个(或两个,或者需要很多)行和很多列。等等。
不确定是否需要,但我显示图像的代码是:
for (int i = 0; i < ImageGrid.RowDefinitions.Count; i++)
{
for (int j = 0; j < ImageGrid.ColumnDefinitions.Count; j++)
{
Image img = new Image();
BitmapImage bitmap = new BitmapImage();
using (var fs = new FileStream(path, FileMode.Open)) // open the image
{
bitmap.BeginInit();
bitmap.StreamSource = fs;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
}
bitmap.Freeze(); // bitmap isn't properly cleaned up and memory leaks can occur if this isn't here
img.Source = bitmap;
img.Margin = new Thickness(10);
img.Stretch = Stretch.Uniform;
Grid.SetRow(img, i);
Grid.SetColumn(img, j);
ImageGrid.Children.Add(img);
}
}
我的网格 XAML 是:
<Grid ShowGridLines="True" Background="DimGray">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="175" Width="0"/>
<ColumnDefinition MinWidth="755" Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Name="lblWinSize" Content="Width, Height"
HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
<TextBox Name="txtnbox" Style="{StaticResource CustomTxtBox}"
TextWrapping="NoWrap" Width="Auto" Height="25" VerticalAlignment="Top"
Margin="10, 20, 10, 0"/>
<Separator Style="{StaticResource VerticalSeparator}"
HorizontalAlignment="Right" Height="Auto" Width="2" Margin="0,10,0,10"/>
<CheckBox Style="{StaticResource CustomCheckBox}"
HorizontalAlignment="Left" Margin="10,50,0,0" VerticalAlignment="Top"/>
<Grid Name="ImageGrid" Grid.Column="1" Margin="10,10,0,10"
ShowGridLines="True" Background="Gray">
<!--this is the grid where the images would go-->
</Grid>
</Grid>
很抱歉该 XAML 的缩进,我无法正确格式化。
行/列在代码中的其他地方定义,但考虑到它会被替换,我认为我不需要粘贴。
同样,如果其他控件更适合,我可以更改为。
【问题讨论】: