Extracting array element in Live Binding

From OPC Labs Knowledge Base
Revision as of 20:54, 4 February 2017 by User (talk | contribs) (Created page with "Sometimes there is a requirement to display just one element of an array value provided by an OPC server. It is easy to take an element of an array in code, but currently (in...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Sometimes there is a requirement to display just one element of an array value provided by an OPC server. It is easy to take an element of an array in code, but currently (in QuickOPC version 2016.2) there is no built-in way to do it with Live Binding.

It is, however, very easy to write a data converter component that extracts the array element. The code has just several lines:

using System;
using System.ComponentModel;
using System.Globalization;
using OpcLabs.BaseLib.Data;

namespace WindowsFormsApplication1
{
    public sealed class ArrayElementConverter : Component, IDataConverter
    {
        public ArrayElementConverter()
        {
        }

        public ArrayElementConverter(IContainer container)
        {
            container.Add(this);
        }

        public object Convert(object value, object parameter, CultureInfo culture)
        {
            var array = (Array) value;
            int index = int.Parse((string) parameter);
            object result = array.GetValue(index);
            return result;
        }

        public object ConvertBack(object value, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException("Inverse conversion is not supported by ArrayElementConverter.");
        }
    }
}

Note that the code is mainly for illustration purposes; a "production quality" code would probably contain better error handling and some other features.

Instructions:

  1. Create Live Binding project in the usual way.
  2. Add an ArrayElementConverter class with the code above (possibly changing the namespace).
  3. Build the project.
  4. Open the form which should contain the binding for an array element.
  5. Drag the ArrayElementConverter component from the Toolbox to the design area of the form.
  6. Add the binding you need. For now, the binding will bind to the whole array.
  7. Select the control with the binding, and perform "Edit Live Bindings".
  8. In Binding Collection Editor, select the binding.
  9. In the property grid, under Value Conversion group, click on the Converter property, click the drop-down button on the right, and select the arrayElementConverter1 component.
  10. In Converter Parameter property row, enter the index of the array element you want to extract. This has to be a valid integer that falls into the array bounds.
  11. Press OK to close the Binding Collection Editor.
  12. Build the project and test it.