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,
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With