如何以编程方式维护wpf中对象的宽高比

时间:2016-10-06 12:38:03

标签: c# wpf

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

  1. 使边框保持纵横比并填充使其在网格内尽可能大
  2. 每当网格向下或向上缩放时制作边框比例(因此不是特别大可能,更像是网格的百分比)
  3. 目前,这是我调整窗口大小的情况:

    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

    所以我希望它能够正确调整大小并保持在白色矩形内。顺便说一句,白色网格有一个边距,你可以看到;-) 提前谢谢!

2 个答案:

答案 0 :(得分:3)

正如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,则此解决方案无效。 我希望它可以帮到你。

答案 1 :(得分:1)

最简单的方法:

UITextField *searchTextField = [_searchBar valueForKey:@"_searchField"];
searchTextField.textAlignment = NSTextAlignmentRight

通过C#:

 <Grid Margin="50">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="50" />
    </Grid.ColumnDefinitions>
    <Border CornerRadius="50,0,0,50"
            Background="Green" />
    <Border CornerRadius="0"
            Grid.Column="1"
            Background="Green" />
    <Border CornerRadius="0,50,50,0"
            Grid.Column="2"
            Background="Green" />

</Grid>

正常:

enter image description here 调整大小:

enter image description here

这对你来说够好吗?