繁体   English   中英

如何在Xamarin.Forms中将视图绑定到Dictionary?

[英]How to bind views to a Dictionary in Xamarin.Forms?

我有View和ViewModel。 在ViewModel中,我创建了一个动态表单(基于表单对象),这个“动态表单”是一个具有N个视图的StackLayout(如条目,选择器......)。

可以说,当用户点击提交按钮时,应用程序需要将表单中字段的所有信息存储在Dictionary<string, object>()

我有一个方法可以通过StackLayout并创建一个新的Dictionary。 我不太喜欢这个aprouch,我想要做的是将Stacklayout的字段绑定到Dictionary。

我创建了一个字段,如下所示:

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

然后我:

stackLayout.Children.Add(entry);

为了设置正确的biding,我是否需要在设置条目属性时使用BindingContext属性,还是应该使用setBiding方法?

我在这里一无所知,可以使用一些指针。 我在stackoverflow上搜索但没找到我需要的东西。

编辑:添加我的ViewModel代码。

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()
    {
    }

}

我删除了一些东西,但这是基本的想法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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