简体   繁体   中英

How can I set the rowspan size of a stacklayout within a grid?

I have laid out an XML page in Xamarin.Forms which has a "stacklayout" within a "grid". I want to programmatically set/change the grid rowspan height.

My XML:

<Grid x:Name="outerGrid">
    <StackLayout x:Name="MyStackLayout" Grid.Row="5" Grid.RowSpan="{Binding MyRowSpanValue}" Grid.Column="0">
        <!-- labels/buttons are added here in code-behind -->
    </StackLayout>
</Grid>

Now in my code-behind, conditionally set it using something like:

if (somevar == 2)
    MyRowSpanValue = 5
else
    MyRowSpanValue = 10

What is the C# code to do this? Mine isn't working, even tried putting this into an "OnAppearing()" override.

Thank for any assistance!

  1. You need to set your BindingContext properly. If you have a view model, you will need to set the binding source in xaml as your page so it can find the property.
  2. You don't specify any columns in your grid , so there is no columns to span for the StackLayout
  3. If this is in your code behind of the xaml file, you don't need to implement INotifyPropertyChanged . Just call OnPropertyChanged(nameof(MyRowSpanValue))

EDIT

If using ViewModel:

First you will need an x:Name="Page" or whatever name you would like to call your page. Then the code for referencing it will look as follows:

<StackLayout x:Name="MyStackLayout"
             Grid.Row="5"
             Grid.RowSpan="{Binding MyRowSpanValue, Source={x:Reference Page}}"
             Grid.Column="0">
        <!-- labels/buttons are added here in code-behind -->
</StackLayout>

Not using a ViewModel

In your page constructor, set the BindingContext=this; and then the xaml/page will look to your code behind for the MyRowSpanValue property.

public YourConstructor()
{
    BindingContext = this; // Code behind will be binding context for XAML
}

When you want to change the value of the property ( used for both situations )

public int MyRowSpanValue { get; set; }

// When you want to change the MyRowSpanProperty
public void ChangeTheValue()
{
    MyRowSpanValue = 3; // Or whatever value you are wanting
    OnPropertyChanged(nameof(MyRowSpanValue));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM