Nic*_*tch 5 silverlight xaml datatemplate silverlight-3.0
我正在尝试以编程方式将事件和元素添加到Silverlight 3.0应用程序中的DataTemplate.我有一个带有依赖项属性的用户控件,我想在其中设置模板,调整它,然后将修改后的版本设置为内部控件.
我的想法是采用进来的DataTemplate,读取它的XAML,调整它,然后使用XamlReader创建一个可以设置为内部控件的修改后的DataTemplate.这种方法的问题是我不知道如何从原始模板中获取XAML(如果它甚至可能.)例如:
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;
}
Run Code Online (Sandbox Code Playgroud)
有人知道:1)是否有办法读取原始XAML,或2)另一种以编程方式修改DataTemplate的方法.
谢谢,
您无法通过代码操作模板(请参阅FrameworkTemplate的文档)。您将获得的最接近的方法是调用 DataTemplateLoadContent来创建所包含的 Xaml 的实例,但您不能使用它来操作内容,并且 Silverlight 内部无法UIElement再次将其转换回 Xaml。
我认为您可以获得的最接近的结果是使您的依赖项对象成为一个指向包含初始 DataTemplate 的 Xaml 资源的 Uri。
然后,您可以将此资源加载到XDocumentXML 中并对其进行操作。随后您可以使用XamlReader来实例化DataTemplate并将其分配给ItemTemplate。