首页 > 解决方案 > UWP 以编程方式绑定动态表单

问题描述

我使用这个模型类创建了一个动态表单:

public class CustomField 
{
    [JsonProperty("uid")]
    public Guid uid { get; set; }

    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("type")]
    public CustomFieldType type { get; set; }
}
public enum CustomFieldType
{
    TEXT = 0,
    MULTI_LINE = 1,
    DATETIME = 2,
    ...
}

我将使用这个模型类来保存自定义字段值:

public class CustomFieldValue
{
    [JsonProperty("uid")]
    public Guid uid { get; set; }

    [JsonProperty("type")]
    public CustomFieldType type { get; set; }

    [JsonProperty("textValue")]
    public string textValue { get; set; }

    [JsonProperty("dateValue")]
    public DateTime dateValue { get; set; }
    ...
}

除了自定义字段,我的基本模型还包含标准输入:

public class BaseModel
{
    [JsonProperty("uid")]
    public Guid uid { get; set; }

    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("description")]
    public string description { get; set; }
    ...

    [JsonProperty("customFieldValues")]
    public List<CustomFieldValue> customFieldValues { get; set; }
}

我的问题是如何以编程方式将自定义字段绑定到下面的视图模型中与标准输入:

public class ViewModel : ViewModelBase
{
   BaseModel cModel;
   ...
   public string name
   {
       get
       {
           if (isLoaded)
               return Model.name;
           else
               return "";
       }
       set
       {
           if (Model.name != value)
           {
               Model.name = value;
               OnPropertyChanged();
               isModified = true;
           }
       }
   }
   ...
   public BaseModel Model
   {
        get
        {
            return cModel;
        }
        set
        {
            cModel = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(name));
            ...
        }
   }
}

在我的视图页面中:

<TextBox x:Name="txtName"
         Text="{x:Bind ViewModel.name, Mode=TwoWay}"
         Style="{StaticResource entryDefault}"
         Header= "Name*"
         PlaceholderText="Enter Name"
         Margin="0,10,0,0"
         Width="800"
         HorizontalAlignment="Left"/>

标签: c#wpfxamlxamarinuwp

解决方案


推荐阅读