3

I have View and a ViewModel. In the ViewModel I create a dynamic form (based on a form object), this "dynamic form" is a StackLayout with a N number of Views (like entries, pickers...).

Lets say that, when the user hits the submit button the app needs to store all the information of the fields from the form in a Dictionary<string, object>().

I had a method that would go through the StackLayout and create a new Dictionary. I didn't quite like this aprouch, what I want to do is bind the Stacklayout's fields to the Dictionary.

I create a field, like this:

var entry = new 
    Keyboard = Keyboard.Numeric,
    HorizontalOptions = LayoutOptions.Fill,
    VerticalOptions = LayoutOptions.CenterAndExpand
};

and then I:

stackLayout.Children.Add(entry);

In order to set the correct biding, do I need to use the BindingContext property from when I'm setting the entry' properties or should I use the setBiding method ?

I'm here clueless here and could use a few pointers. I searched on stackoverflow but didn't find what I needed.

Edit: adding my ViewModel code.

class FormViewModel : INotifyPropertyChanged
{
    public ICommand RegisterCommand { get; set; }

    private StackLayout _layout;

    private Answer Answer;

    private Dictionary<string, object> dictionary = new Dictionary<string, object>();


    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public FormViewModel(Form form, StackLayout layout)
    {
        _layout = layout;

        RegisterCommand = new Command(SaveForm);

    }

    public void SaveForm()
    {
    }

}

I removed a few things, but thats the basic idea.

Carlos
  • 388
  • 2
  • 13
  • 33
  • 1
    Actually, you'll set both. For each component you create, you'll set the input property (and maybe a ValueConverter to it) to the `object` value to the corresponding element on dictionary. – Diego Rafael Souza Feb 14 '18 at 19:23
  • Hmm, I'm wondering if it's possible to [create a class dynamically](https://stackoverflow.com/questions/47767871/dynamically-create-c-sharp-class-or-object) and write a property for each view of your StackLayout in it then set those views' desired values binding to those properties, and in the setter of each binded property, updating your dictionary!!! – VahidShir Feb 14 '18 at 21:31
  • And of course, setting BindingContext of those views to aforementioned class! – VahidShir Feb 14 '18 at 21:35
  • @Carlos Can you edit the question and add the associated ViewModel code? – Brandon Minnick Feb 14 '18 at 22:22
  • This answer helped solve the problem https://stackoverflow.com/questions/36985634/xamarin-forms-databinding-separator – Carlos Feb 15 '18 at 12:04

1 Answers1

0

You need to use ObservableDictionary and watch events in case of update, add or delete.

eakgul
  • 3,658
  • 21
  • 33