我以编程方式向网格添加具有特定宽度和高度的 Border
。但是,我想获得以下之一:
- 使边框保持宽高比,并在网格内填充尽可能大
- 每当网格按比例缩小或放大时使边框缩放(所以不是特别最大可能,更像是网格的百分比)
目前这是我调整窗口大小时的情况:
Color borderColor = (Color)ColorConverter.ConvertFromString(BorderColor);
Color backgroundColor = (Color)ColorConverter.ConvertFromString(BackgroundColor);
Border border = new Border();
border.BorderThickness = new Thickness(BorderSize);
border.CornerRadius = new CornerRadius(TopLeftCornerRadius, TopRightCornerRadius, BottomRightCornerRadius, BottomLeftCornerRadius);
border.BorderBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom(BorderColor));
border.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(BackgroundColor));
border.Width = Width;
border.Height = Height;
border.Margin = new Thickness(10);
previewgrid.Children.Add(border);
正常情况:
缩放情况:
所以我希望它能适本地调整大小并留在白色矩形内。顺便说一句,白色网格有边距,如您所见;-)提前致谢!
正如 lerthe61 所建议的,只需使用 Viewbox将其 Stretch
属性设置为 Uniform
:
Color borderColor = (Color)ColorConverter.ConvertFromString(BorderColor);
Color backgroundColor = (Color)ColorConverter.ConvertFromString(BackgroundColor);
Border border = new Border();
border.BorderThickness = new Thickness(BorderSize);
border.CornerRadius = new CornerRadius(TopLeftCornerRadius, TopRightCornerRadius, BottomRightCornerRadius, BottomLeftCornerRadius);
border.BorderBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom(BorderColor));
border.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(BackgroundColor));
border.Width = Width;
border.Height = Height;
border.Margin = new Thickness(10);
Viewbox viewBox = new Viewbox();
viewBox.Stretch = Stretch.Uniform;
viewBox.Child = border;
previewgrid.Children.Add(viewBox);
请注意,如果 previewgrid
是 Canvas
,则此解决方案不起作用。希望对您有所帮助。
我是一名优秀的程序员,十分优秀!