How to create a simple ObjectDataSource Control for Silverlight 3.0 and use Element Binding.

While I was sitting here a Saturday morning and was thinking about what to do, I decided to simply create a light weight ObjectDataSource for fun, only to have a blog post to write ;)

As you may now the every XAML element are objects, so it’s easy to add extra controls and functionality to XAML. Here is a simple example of a ObjectDataSource control with only one feature, to call a single method and populate a DataGrid control:

<data:DataGrid ItemsSource="{Binding Data, ElementName=dds}" ></data:DataGrid>
        
<ds:ObjectDataSource x:Name="dds" LoadMethodName="GetStrings">
   <ds:ObjectDataSource.SourceObject>
      <o:MyObject/>
   </ds:ObjectDataSource.SourceObject>
</ds:ObjectDataSource>


Silverlight 3.0 supports Element Binding, so I bind the Data property of my ObjectDataSource to the DataGrid’s ItemSource. The ObjectDataSource has two properties, LoadMethodName, to specify the method to get the data that should be added to the DataGrid. The SourceObject takes an object of any kind, and in this case it’s the object that has the specified LoadMethodName:

public class MyObject
{
   public IEnumerable<string> GetStrings()
   {
      return new List<String>() { "test", "test1", "test2" };
   }
}

 

The implementation of the ObjectDataSource is kind of simple, it only make sure to invoke the LoadMethodName when the SourceObject property is set to the ObjectDataSource:

public class ObjectDataSource : Control, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private object _sourceObject;
    private object _data;

    public object SourceObject
    {
       get { return _sourceObject; }
       set
       {
            this._sourceObject = value;
            this.Data = this._sourceObject.GetType().InvokeMember(
                                  LoadMethodName, 
                                  System.Reflection.BindingFlags.InvokeMethod, 
                                  null, 
                                  this._sourceObject, 
                                   null);
       }
    }

       
    public string LoadMethodName { set; get; }


    public object Data
    {
       get { return this._data; }
       set
       {
           this._data = value;
           RaisePropertyChanged("Data");
       }
    }


    protected void RaisePropertyChanged(string propertyName)
    {
       var propertyChanged = this.PropertyChanged;

       if (propertyChanged != null)
           propertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

This ObjectDataSource is not a sophisticated one, as you may see, and very simple implemented, and doesn’t even do an asynchronous call.

No Comments