Silverlight Quick Tip: Dynamically Updating Class Fields/Properties
In previous post (here) I blogged about displaying values of class/control in runtime and displaying them in Visual Studio - like property window. Today I’ll show how to push them back to the class instance.
In previous post I’ve stored values in “ObservableCollection<FieldsPropertiesData>” for easy databinding and connected this ListBox control. In order to get user input I’ve created TwoWay databinding in DataTemplate – here is updated data template:
<Style TargetType="local:FiledPropertyData">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:FiledPropertyData">
<Grid ToolTipService.Placement="Mouse" Width="{TemplateBinding Width}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0,0,10,0"/>
<TextBox Text="{Binding FieldValue, Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Right"
IsEnabled="{Binding IsReadOnly, Converter={StaticResource boolToEnabledConverter}}" Grid.Column="1"/>
<ToolTipService.ToolTip>
<ToolTip Background="Transparent" BorderBrush="Transparent" BorderThickness="0" Padding="0" Margin="5">
<ToolTip.Content>
<Border Background="PaleGoldenrod" BorderBrush="Black" BorderThickness="2" CornerRadius="5" Padding="5" Margin="0">
<TextBlock Text="{Binding Description}"/>
</Border>
</ToolTip.Content>
</ToolTip>
</ToolTipService.ToolTip>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Now at the setter of the “FieldValue” property all I need is to push it back to the instance.
I’ve create function, which accepts FieldName, FieldType (from data already exits in the file from the loading) and new value:
private static void SetFieldValue(string FieldName, Type FieldType, object TheValue)
{
Assembly asm = Assembly.GetExecutingAssembly();
Type type = asm.GetType("SAMPLE_TYPE_TO_UPDATE");
FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
var fieldInfo = from field in fields
where field.FieldType == FieldType && field.Name == FieldName
select field;
FieldInfo theField = fieldInfo.FirstOrDefault();
if (null != theField)
if (value.GetType() == FieldType)
theField.SetValue(if (theField.IsStatic) ? null : TheInstance, TheValue);
else //In case of value changed by databinding in most cases ToString() result will be here,
//hence need to convert
theField.SetValue(if (theField.IsStatic) ? null : TheInstance, Convert.ChangeType(TheValue, FieldType, null));
fieldInfo = null;
fields = null;
type = null;
asm = null;
}
That’s it… Now the data dynamically displayed, updated by user and pushed back to the instance of the object.
Enjoy,
Alex