我正在尝试以编程方式将事件和元素添加到 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;
}
有人知道:1) 是否有读取原始 XAML 的方法,或 2) 以编程方式修改 DataTemplate 的另一种方法。
谢谢,
最佳答案
您不能通过代码操作模板(请参阅 FrameworkTemplate 的文档)。您将获得的最接近的是调用 DataTemplate 的 LoadContent
创建包含的 Xaml 的实例,但您不能使用它来操作内容,并且 Silverlight 内部无法转换 UIElement
再次回到 Xaml。
我认为你能得到的最接近的方法是使你的依赖对象成为一个指向包含初始 DataTemplate 的 Xaml 资源的 Uri。
然后,您可以将此资源加载到 XDocument
中。并将其作为 XML 进行操作。随后您可以使用XamlReader
以 DataTemplate
为例并将其分配给 ItemTemplate
.
关于silverlight - 如何以编程方式修改数据模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1903287/