XamlReader 生成 DataTemplate 的问题

2023-11-25

我正在尝试在我的 WPF 项目中实现下面的代码,以便为具有动态列的 DataGrid 动态生成 DataTemplates。我在 StackOverflow 上找到了代码here

public DataTemplate Create(Type type)
{
  return (DataTemplate)XamlReader.Load(
          @"<DataTemplate
            xmlns=""http://schemas.microsoft.com/client/2007"">
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
            </DataTemplate>"
   );
}

但是,在 XamlReader.Load 代码上,我收到错误“无法从“字符串”转换为“System.Xaml.XamlReader”。

我试图通过将代码更改为来解决这个问题:

return (DataTemplate)XamlReader.Load(XmlReader.Create(

但我收到有关在字符串中传递无效字符的错误。

另外,我不确定如何将 TextBlock 传递给此代码。我想我只是创建一个 TextBlock 并将其作为 Type 参数传递,但我收到错误“无法从 'System.Windows.Controls.TextBlock' 转换为 'System.Type'

任何帮助表示赞赏。


public DataTemplate Create(Type type)
{
    StringReader stringReader = new StringReader(
    @"<DataTemplate 
        xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> 
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/> 
        </DataTemplate>");
    XmlReader xmlReader = XmlReader.Create(stringReader);
    return XamlReader.Load(xmlReader) as DataTemplate;
}

像这样称呼它

TextBlock textBlock = new TextBlock();
Create(textBlock.GetType());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XamlReader 生成 DataTemplate 的问题 的相关文章

随机推荐