We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How do I set BindingContext for PopupView?

I'm trying to implement a popup that displays a list of items using a template and I'm having a problem binding the data context. The code I have is:

private void HandlePopupMessage(PopupMessage popupMessage)
        {
            var popupLayout = new SfPopupLayout(); 
 
            var template= Application.Current.Resources[$"{popupMessage.ViewType}PopupTemplate"] as DataTemplate;
            popupLayout.PopupView.ContentTemplate=template;
            var getPopupBindingContextMessage = new GetPopupBindingContextMessage(popupMessage.ViewType, popupMessage.ViewOptions);
            Messenger.Default.Send(getPopupBindingContextMessage);
            popupLayout.PopupView.BindingContext=getPopupBindingContextMessage.Result;
            popupLayout.Show();
        }

NB:GetPopupBindingContextMessage is a special message that throws if the receiver hasn't populated its result and the debugger shows that popupLayout.BindingContext is an instance of the class.

The template I'm using is defined in App.Xaml as:

 <DataTemplate x:Key="WorkflowSelectorPopupTemplate" x:Name="WorkflowSelectorPopupTemplate" x:DataType="{x:Type vm:PopupWorkflowSelectorViewModal}">
                <Grid>
                    <ListView ItemsSource="{Binding AvailableWorkflows}"
                              SelectedItem="{Binding SelectedWorkflow}"
                              BackgroundColor="{StaticResource CorporateYellow}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <Grid BackgroundColor="{StaticResource CorporateYellow}">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="10" />
                                            <ColumnDefinition Width="*" />
                                        </Grid.ColumnDefinitions>
                                        <Label Text="{Binding Name}" Grid.Column="1" FontAttributes="Bold" VerticalOptions="Center" VerticalTextAlignment="Center" />
                                    </Grid>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Grid>
            </DataTemplate>

The view model is:

    internal class PopupWorkflowSelectorViewModal
    {
        public Func<Workflow, DataEntryViewCompleteDocumentCreationMessage> CreateCompleteDocumentCreationMessage { get; }

        public PopupWorkflowSelectorViewModal(IViewOptions viewOptions,
            Func<Workflow, DataEntryViewCompleteDocumentCreationMessage> createCompleteDocumentCreationMessage)
        {
            var workflowSelectorViewOptions = (WorkflowSelectorViewOptions) viewOptions;
            CreateCompleteDocumentCreationMessage = createCompleteDocumentCreationMessage;
            AvailableWorkflows = new List<Workflow>(workflowSelectorViewOptions.AvailableWorkflows);
        }

        public IEnumerable<Workflow> AvailableWorkflows { get; }
        public Workflow SelectedWorkflow { get; set; }
    }

The template is being loaded and used because I can see a yellow block and if I modify it to include buttons they appear. However the binding appears not to be working. There are no errors in the output window but it never calls the AvailableWorkflows property on the view model object.


6 Replies

MA Mr Andrew Cope December 17, 2018 03:56 PM UTC

Hmph. I found the answer. The solution is to set popupLayout.BindingContext instead of popupLayout.PopupView.BindingContext.

Could someone explain why? It seems counter-intuitive.


AA Arulraj A Syncfusion Team December 18, 2018 04:03 PM UTC

Hi Andrew,  
  
Thanks for the update. 
  
If we set the binding context to popupLayout.PopupView, BindingContext does not set to Popup. Since SfPopupLayout is the parent for popupview and so we need to set the binding context to SfPopupLayout to get it work.  

Let us know whether this helps also if you need any further assistance on this. 

Regards, 
Arulraj A 



JR Jassim Rahma May 28, 2019 04:00 AM UTC

I binded to the SfPopup but still not getting the data shown in my Label.

Here is my XAML:

<ContentPage.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="EditLocationTemplate">
            <ContentView BackgroundColor="White" x:Name="EditLocationContentView">
                <StackLayout Padding="15" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                    <Label x:Name="LabelNewAdLocationCountry" Text="{Binding country_name}" />
                    <Label x:Name="LabelNewAdLocationAddress" Text="{Binding location_address}" />
                </StackLayout>
            </ContentView>
        </DataTemplate>
    </ResourceDictionary>
</ContentPage.Resources>


and this is my code:

private void ButtonNewAdLocationEdit_Clicked(object sender, EventArgs e)
{
    SfButton editButton = ((SfButton)sender);

    location_id = Convert.ToInt32(editButton.CommandParameter);

    popupLayout = new SfPopupLayout();

    popupLayout.BindingContext = new ViewModelAdLocation();

    popupLayout.PopupView.AppearanceMode = AppearanceMode.TwoButton;

    popupLayout.PopupView.AcceptButtonText = "Save";
    popupLayout.PopupView.DeclineButtonText = "Cancel";

    // Set TwoButton Appearance mode for getting 2 buttons in the footer
    popupLayout.PopupView.ShowFooter = true;

    // Setting the ContentView as the content of the popup
    popupLayout.PopupView.ContentTemplate = (DataTemplate)Resources["EditLocationTemplate"];
    popupLayout.PopupView.AnimationMode = AnimationMode.SlideOnTop;
    popupLayout.PopupView.ShowCloseButton = true;
    popupLayout.StaysOpen = true;
    popupLayout.PopupView.IsFullScreen = true;

    popupLayout.PopupView.HeaderTitle = "Ad Location";

    popupLayout.IsOpen = true;
}


Kindly help...


Thanks,



SP Subburaj Pandian Veluchamy Syncfusion Team May 28, 2019 01:44 PM UTC

Hi Jassim, 
 
Based on the provided code, we have prepared a sample and tested the reported issue "Popup view content is not updated when we define binding context to popup layout" and it is working fine as expected from our end. We already fixed the similar issue with Popup in our last updates. We have tested with our latest update version 17.1.0.38 and 17.1.0.47. 
 
Please find the attached sample for your reference, 
  
  
Please check the sample and let us know whether you’re using latest update? if issue still persist, kindly share Syncfusion product version and issue reproducing platform. It will be helpful for us to check it out and provide you with an appropriate solution. 
  
Regards,
Subburaj Pandian V 



JR Jassim Rahma May 29, 2019 03:06 AM UTC

I am not getting that... although my code returns the data properly when debugging it

Here is my ViewModel:

using System;
using System.Collections.Generic;
using System.Text;
using Syncfusion.ListView.XForms;
using Syncfusion.XForms.PopupLayout;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace MyApp
{
    public class ViewModelAdLocation : INotifyPropertyChanged
    {
        public Command<object> TapCommand { get; set; }
        SfPopupLayout popupLayout;

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string name)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

        public int ad_location_id { get; set; }
        public string country_name { get; set; }
        public double? location_latitude { get; set; }
        public double? location_longitude { get; set; }
        public string location_address { get; set; }
        public string telephone { get; set; }
        public bool is_readonly { get; set; }

        public ViewModelAdLocation()
        {
            TapCommand = new Command<object>(EditButtonTapped);
        }

        private void EditButtonTapped(object obj)
        {
            popupLayout = new SfPopupLayout();
            popupLayout.PopupView.HeightRequest = 500;
            popupLayout.PopupView.WidthRequest = 300;
            // popupLayout.BindingContext = ModelBinding;

            popupLayout.PopupView.ContentTemplate = new DataTemplate(() =>
            {
                var mainStack = new StackLayout();
                mainStack.BackgroundColor = Color.AliceBlue;

                var image = new Image();
                image.SetBinding(Image.SourceProperty, new Binding("ContactImage"));

                var grid = new Grid();
                var NameLabel = new Label()
                {
                    Text = "Customer Name  "
                };

                NameLabel.HorizontalOptions = LayoutOptions.Start;

                var label1 = new Entry()
                {

                };

                label1.SetBinding(Entry.TextProperty, new Binding("ContactName"));
                label1.HorizontalOptions = LayoutOptions.Start;

                var NumberLabel = new Label()
                {
                    Text = "HERE LOCATIO ID"
                };
                NumberLabel.HorizontalOptions = LayoutOptions.Start;


                var label2 = new Entry()
                {

                };

                label2.SetBinding(Entry.TextProperty, new Binding("ContactNumber"));
                label2.HorizontalOptions = LayoutOptions.Start;

                grid.Children.Add(NameLabel, 0, 0);
                grid.Children.Add(label1, 1, 0);
                grid.Children.Add(NumberLabel, 0, 1);
                grid.Children.Add(label2, 1, 1);

                mainStack.Children.Add(image);
                mainStack.Children.Add(grid);

                return mainStack;
            });

            popupLayout.PopupView.ShowHeader = false;
            popupLayout.PopupView.ShowFooter = false;
            popupLayout.HeightRequest = 500;
            popupLayout.WidthRequest = 500;
            popupLayout.Show();
        }

    }
}


and this is how I get the data:

public class LocationData
{
    public int ad_location_id { get; set; }
    public string country_name { get; set; }
    public double? location_latitude { get; set; }
    public double? location_longitude { get; set; }
    public string location_address { get; set; }
    public string telephone { get; set; }
    public bool is_readonly { get; set; }
}


protected override async void OnAppearing()
{
    var client = new HttpClient();

    client.BaseAddress = new Uri("https://www.domain.com/populate.php");

    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("language", "EN"),
        new KeyValuePair<string, string>("ad", ad_id)
    });

    var response = await client.PostAsync("https://www.domain.com/populate.php", content);

    var data = await response.Content.ReadAsStringAsync();

    var result = JsonConvert.DeserializeObject<List<ViewModelAdLocation>>(data);
    ObservableCollection<object> trends = new ObservableCollection<object>();

    for (int i = 0; i < result.Count; i++)
    {
        LocationData data1 = new LocationData()
        {
            ad_location_id = result[i].ad_location_id,
            country_name = result[i].country_name,
            location_address = result[i].location_address,
            telephone = result[i].telephone
        };

        trends.Add(data1);
    }

    // await DisplayAlert("ID", Convert.ToString(ad_id), "OK");

    ListViewNewAdLocations.ItemsSource = trends;

    BusyIndicatorNewAdLocation.IsVisible = false;

    ListViewNewAdLocations.IsVisible = true;
}




SP Subburaj Pandian Veluchamy Syncfusion Team May 29, 2019 12:50 PM UTC

Hi Jassim, 
  
Thank you for your update. 
  
We checked the Model and ViewModel code of the shared details. You are collecting data from the server and loading the data into the list view. 
  
Please clarify the details below to prepare a sample for your case, 
  
·       In the ButtonNewAdLocationEdit Clicked method you have created new ViewModelAdLocation instacce to bind as a binding context for the popup layout. In this view model, you have not defined any value for country name and location address which is a binding property of the label hosted in pop up view. What are you exactly doing in this method? 
  
·       In the EditButtonTapped method you have created another popup and the binding property ContactImage and ContactName which are not there in ViewModel or in model. 
  
Can you please explain about the issue you’re experiencing, in which method popup content is not displayed? How you are trying to show popup. If it is in button click where it is loaded. 
  
Please share above details to replicate the issue from our end, so that we can check and provide you the solution. 
  
Regards,
Subburaj Pandian V        


Loader.
Live Chat Icon For mobile
Up arrow icon