Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Creating and using dynamic properties in a Silverlight Dataform

0.00/5 (No votes)
25 Aug 2010 1  
Creating properties at runtime within a model that can then be used to bind to a Dataform
If there is a situation where properties need to be created and displayed in a data form at runtime (i.e.your properties / class attributes are not defined at design time but are returned from a web service at runtime) then indexed properties can be used to create "dynamic" properties at runtime. I used such properties to bind to a control (I required to do this in a Dataform), but other controls can be used as well.

Create an indexed property (amongst other properties) within your model.

[Editable(false, AllowInitialValue = false)]
[Display(Name = "", AutoGenerateField = false)]
public object this[string name]
{
   get
      {
         if (properties.ContainsKey(name))
            {
                return properties[name];
            }
            return null;
      }
    set
      {
            properties[name] = value;
      }
}


Note: The attributes defined before this property (i.e. Display and Editable), are only requried for a Dataform.

Within the viewmodel, set the "aName" property as shown here.
This name and value pair will actually be coming from a dynamic resource such as a database or a web service.

foreach (MyModel objTemp in myInstance)
{
            string strProperty = "aName";
            objTemp[strProperty] = "value" + i++;
}


Finally, create xaml on the fly (say using a StringBuilder) including code for each of the "dynamic" properties within the dataform. I have just used "aName" here, but any property designed at runtime can be defined here, maybe, using a for each loop.

<dataFormToolkit:DataForm x:Name="dataForm"
ItemsSource="{Binding Mode=OneWay}"
LabelPosition="Left">
  <dataFormToolkit:DataForm.EditTemplate>
    <DataTemplate>
        <StackPanel>
          <dataFormToolkit:DataField  Label="aName">
            <TextBox Text="{Binding [aName], Mode=TwoWay}" />
            </dataFormToolkit:DataField>
        </StackPanel>
    </DataTemplate>
  </dataFormToolkit:DataForm.EditTemplate>
</dataFormToolkit:DataForm>


Once this is done, the dataform will display this property within the view. Thus, any number of properties can be set at runtime and then these can be bound to the view.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here