IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

IronRuby Tip: Data Binding Silverlight Elements to IronRuby Objects

When I was playing around with Silverlight and IronRuby, I ran into a problem with data binding and IronRuby objects. This post is to let you know about it and hand you the workaround as well.

The Problem

You have an IronRuby class. You fill it with data and set it as the data context of your Silverlight element.
The result: the values are not presented on the Silverlight page.

Detailed steps to reproduce:

1. Create an IronRuby class. For example:

class Person
  attr_accessor :full_name
  def initialize(full_name)
    self.full_name = full_name
  end
end


2. Create an instance of that class and set it as the data_context of an element:

shay = Person.new "Shay Friedman"
@root.data_context = shay


3. Set the element to present the data:

<StackPanel>
  <TextBlock>You name  is </TextBlock>
  <TextBlock Text="{Binding full_name}"/>
</StackPanel>


4. Run the page – nothing is shown.

 

The Reason

With the help of Jimmy Schementi I’ve figured out what the problem was. Silverlight 3.0 elements can only do reflection-based data binding. IronRuby objects are based on ICustomTypeDesciptor, which means that the attributes cannot be read using reflection. Bummer.

The Workaround

Instead of using an IronRuby class, use a CLR class. This means that in order to make it work, the work flow should be as follows:

1. Create a C#/VB.Net class. For example (assume this appears in “person.dll”):

class Person
{
  public string FullName { get; set; }
  public Person(string fullName)
  {
    FullName = fullName;
  }
}


2. Create an instance of that class in IronRuby and set it as the data_context of an element:

require "person.dll"
shay = Person.new("Shay Friedman")
@root.data_context = shay


3. Set the element to present the data:

<StackPanel>
  <TextBlock>You name  is </TextBlock>
  <TextBlock Text="{Binding FullName}"/>
</StackPanel>


4. Run the page – everything works as expected.

All the best,
Shay.

Pingbacks and trackbacks (1)+

Add comment