How do I set a Frame's height equal to its width in C# Markup?

Viewed 269

In Microsoft's Xamarin documentation, they have this example here that shows how to do it with XAML, but I have some frames that I am generating dynamically so I need to be able to do it in C#.

Here is the XAML code to do it, can anyone translate this into C# for me?

<BoxView Color="Red"
     WidthRequest="200"
     HeightRequest="{Binding Source={RelativeSource Self}, Path=WidthRequest}"
     HorizontalOptions="Center" />

Thank you!

3 Answers

Usually in c# you have the value in a variable; simply use that variable for both properties:

        int size = 200;
        var view = new BoxView() { WidthRequest = size, HeightRequest = size };

If you already have a view with WidthRequest set, then:

view.HeightRequest = view.WidthRequest;
<BoxView Color="Red"
 WidthRequest="200"
 HeightRequest="{Binding Source={RelativeSource Self}, Path=Width}"
 HorizontalOptions="Center" VerticalOptions="Center" />

You can use setBinding method(), like code below shows:

    var boxview=new BoxView();
    boxview.Color=Color.CornflowerBlue;
    boxview.HorizontalOptions = LayoutOptions.Center;
    boxview.VerticalOptions = LayoutOptions.Center;
    boxview.WidthRequest=100;
    boxview.setBinding(BoxView.HeightProperty,new Binding("WidthRequest"),source:boxview);
Related