Making a Viewbox scale vertically but stretch horizontally

后端 未结 4 1527
南旧
南旧 2020-12-03 01:36

I want to make a Viewbox (or something similar) that scales only its height, and then stretches its content horizontally.

If I do this:

         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 02:22

    I'm pretty sure the answer is "not easily".

    Here's an idea that seems to work but it's kind of clunky:

    1. Throw your StackPanel into a UserControl (UserControl1 in the example below).

    2. Place two copies of this UserControl into a container (a Grid in the example below).

      a. Align the first copy top/left so that it remains at its default size. This copy is strictly for measurement purposes and should have its Visibility set to Hidden.

      b. Place the second copy inside a Viewbox. This copy is the one the user will actually see.

    3. Use a MultiBinding with a MultiValueConverter to adjust the width of the second UserControl so that it has the correct aspect ratio before it gets expanded by the Viewbox.

    Here's the markup:

    
        
        
            
                
                    
                        
                        
                        
                    
                
            
        
    
    

    Here's the MultiValueConverter

    public class WidthAdjuster : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var rawHeight = (double)values[0];
            var containerWidth = (double)values[1];
            var containerHeight = (double)values[2];
            var ratio = containerWidth / containerHeight;
            return rawHeight * ratio;
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Result for 525 x 350 container

    alt text

提交回复
热议问题