views:

309

answers:

2

I am successfully declaring a data template in a code behind as follows:

    private static DataTemplate CreateTemplate(string sortMemberPath, HorizontalAlignment horzAlignment)
    {
        const string xamlFormat
            =
            "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" >"
            + "<StackPanel > "
            + "  <TextBlock Margin=\"2,0\" VerticalAlignment=\"Center\"  HorizontalAlignment=\"_HALIGNMENT_\"  "
            +
            "              Text=\"hello there\">   "
            + "  </TextBlock> "
            + "</StackPanel>"
            + "</DataTemplate>";

        return (DataTemplate) XamlReader.Load(xamlReturned);
    }

But now I want to add a size changed handler by changing the line:

            + "<StackPanel > "

to

            + "<StackPanel  SizeChanged="SizeChangedHandler" > "

I have the method "SizeChangedHandler" declared in the code behind. This results in a xaml parse error when the control attempts to load at runtime. I suspect that it can't find the handler "SizeChangedHandler". How can I specify this handler so that the xaml parser is happy.

+1  A: 

You could try something like:

  dataTemplate.VisualTree.AddHandler(StackPanel.SizeChangedEvent, new SizeChangedEventHandler(SizeChangedHandler));

Edit:

Ok, for Silverlight you could try with the LoadContent method of the DataTemplate that returns and UIElement to which you can atach the event. Sorry I don't have VS ready to test and see if it works atm.

Pop Catalin
It looks like in Silverlight 2 that a DataTemplate does not expose a VisualTree property.
Phillip Ngan
@Phillip Ngan see my edit.
Pop Catalin
A: 

It won't work (LoadContent). I'm able to get reference to the control defined within DataTemplete but it doen't intercat with the event. It won't raise any events from DataTemplate control.

Michal