gpt4 book ai didi

c# - 如何以编程方式保持wpf中对象的纵横比

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:04 26 4
gpt4 key购买 nike

我以编程方式向网格添加具有特定宽度和高度的 Border。但是,我想获得以下之一:

  1. 使边框保持宽高比,并在网格内填充尽可能大
  2. 每当网格按比例缩小或放大时使边框缩放(所以不是特别最大可能,更像是网格的百分比)

目前这是我调整窗口大小时的情况:

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);

正常情况:

enter image description here

缩放情况:

enter image description here

所以我希望它能适本地调整大小并留在白色矩形内。顺便说一句,白色网格有边距,如您所见;-)提前致谢!

最佳答案

正如 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);

请注意,如果 previewgridCanvas,则此解决方案不起作用。希望对您有所帮助。

关于c# - 如何以编程方式保持wpf中对象的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com