Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding x:Load, updating bound value doesn't load the control (UWP)

I have a grid element with the x:Load attribute bound to a variable in the page:

Page.xaml

<Page>
...
    <Grid x:Name="grd" x:Load="{x:Bind LoadGrid, Mode=OneWay}">

Page.xaml.cs

public sealed partial class Page : Page
...
bool LoadGrid;

After receiving the passed argument from the OnNavigatedTo event handler, I set the value of LoadGrid accordingly:

request = (Request) e.Parameter;

if (request == null)
    LoadGrid = false;
else {
    LoadGrid = true;
    InitializeComponent(); // Tried adding this to refresh the controls.
    grd.Loaded += grd_Loaded;
}

When the line grd.Loaded += grd_Loaded; is executed, an ArgumentException is thrown:

An exception of type 'System.ArgumentException' occurred ...
Delegate to an instance method cannot have null 'this'.

I check and the value of grd is null even though the x:Load property is true and the binding mode is OneWay (the control "checks" for updates in the bound value).

Edits

ATTEMPT 1

Calling this.InitializeComponent() to re-init the controls.

ATTEMPT 2 suggested by @touseefbsb:

Use the MVVM approach to create an event for updating the property value.

ATTEMPT 3

Tried .FindName("grd") after setting the load value, didn't work.

like image 575
Phantom Avatar asked Oct 15 '25 03:10

Phantom


1 Answers

Unlike in prior XAML platforms, the OnNavigated method is called before the visual tree is loaded.

So, you could register the Grid's loaded event in the Page's loaded event handler like the following:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    var request = e.Parameter;

    if (request == null)
        LoadGrid = false;
    else
    {
        LoadGrid = true;
        InitializeComponent();
        this.Loaded += BlankPage1_Loaded;
    }
 }

private void BlankPage1_Loaded(object sender, RoutedEventArgs e)
{
    grd.Loaded += Grd_Loaded;
}

private void Grd_Loaded(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("Grd loaded.");
}
like image 66
Xie Steven Avatar answered Oct 18 '25 01:10

Xie Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!