简体   繁体   中英

How to bind views to a Dictionary in Xamarin.Forms?

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.

您需要使用ObservableDictionary并在更新,添加或删除时监视事件。

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