views:

782

answers:

1

I'm trying to programmatically add events and elements to a DataTemplate in a Silverlight 3.0 app. I have a User Control with a dependency property where I would like to take the template that's set, tweak it, and then set the modified version to an inner control.

The idea I have is to take the DataTemplate that comes in, read its XAML, tweak it, and then use the XamlReader to create a modified DataTemplate that can then be set to the inner control. The issue with this approach is I don't know how to get the XAML from the originalal template (if it's even possible.) For example:

protected virtual void OnItemTemplateChanged(DependencyPropertyChangedEventArgs e)
{
    // Get the original Xaml from the set template
    //string originalXaml = ???

    // Modify the template
    string newXaml = originalXaml.Replace("foo", "bar"); // for example

    // Create a new template from the modified XAML
    DataTemplate newTemplate =  (DataTemplate)XamlReader.Load(newXaml);

    // Update the inner template
    this._childDropdown.ItemTemplate = newTemplate;
}

Does someone know either: 1) if there's a way to read the original XAML, or 2) another approach to programmatically modify the DataTemplate.

Thanks,

+1  A: 

You cannot manipulate the template via code (see documentation for FrameworkTemplate). The closest you are going to get is to call the DataTemplate's LoadContent to create an instance of the contained Xaml but you can't use that to manipulate the contents and there is no way inside Silverlight to convert a UIElement back to Xaml again.

The nearest I think you can get is to make your dependency object a Uri pointing to a Xaml resource that contains the initial DataTemplate.

You can then load this resource into an XDocument and manipulate it as XML. Subsequently you can use XamlReader to instance the DataTemplate and assign it to ItemTemplate.

AnthonyWJones
I (grudgingly) reworked my project so that it doesn't require manipulation of the DataTemplate. It's not what I wanted but at least I'm not wasting any more time trying to do this. Thanks, I hope a future version of Silverlight allows some programmatic manipulation of the DataTemplate.
Nick Gotch
I think what I'd like to see as the ability to replace an ItemsControl ItemContainerGenerator with custom generator which we can't at the moment, I'll have to look up SL4 see if it allows that.
AnthonyWJones