Problems with XamlReader generating DataTemplate

别等时光非礼了梦想. 提交于 2019-12-30 19:52:08

问题


I'm trying to implement the code below in my WPF project in order to generate DataTemplates on the fly for a DataGrid with dynamic columns. I found the code on 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>"
   );
}

However, on the XamlReader.Load code, I get the error "cannot convert from 'string' to 'System.Xaml.XamlReader'.

I tried to get around this by changing the code to:

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

but I get errors about passing invalid characters in the string.

Also, I am unsure how to pass a TextBlock to this code. I imagined I would just create a TextBlock and pass it as the Type argument, but I get the error "cannot convert from 'System.Windows.Controls.TextBlock' to 'System.Type'

Any help appreciated.


回答1:


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;
}

Call it like this

TextBlock textBlock = new TextBlock();
Create(textBlock.GetType());



回答2:


I replicated your code with the workaround for XmlReader and it worked fine without any issues. Please try this:

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

This should work.



来源:https://stackoverflow.com/questions/7170937/problems-with-xamlreader-generating-datatemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!