XamlReader生成DataTemplate的问题 [英] Problems with XamlReader generating DataTemplate
问题描述
我正在尝试在WPF项目中实现以下代码,以便为具有动态列的DataGrid动态生成DataTemplates。我在此处
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>"
);
}
但是,在XamlReader.Load代码上,出现错误无法转换从字符串到 System.Xaml.XamlReader。
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.
此外,我不确定如何将TextBlock传递给此代码。只需创建一个TextBlock并将其作为Type参数传递,但出现错误无法从'System.Windows.Controls.TextBlock'转换为'System.Type'
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'
感谢任何帮助。
推荐答案
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());
这篇关于XamlReader生成DataTemplate的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!