DataTemplate与代码隐藏的转换器

我正在尝试在代码隐藏中加载一个DataTemplate,但是如果我删除转换器它可以正常工作……但是只要我把它放在那里,它就会爆炸。 现在,我确实将我的状态设置为命名空间,并将引用放在XAML中。 例如:

   

这是我生成DataTemplate的方法:

 private DataTemplate GenerateStatRowDataTemplate() { ParserContext pc = new ParserContext(); pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); pc.XmlnsDictionary.Add("xcdg", "http://schemas.xceed.com/wpf/xaml/datagrid"); string statRowTemplate = ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; StringReader stringReader = new StringReader(statRowTemplate); XmlReader xmlReader = XmlReader.Create(stringReader); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(statRowTemplate.ToString())); DataTemplate dt = (DataTemplate)XamlReader.Load(ms,pc); dt.LoadContent(); return dt; } 

我究竟做错了什么? 可能是我必须在后面的代码中定义我的转换器吗?

我的转换器

 public class StatCellConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Debug.WriteLine(value); if (value.Equals("#DIV/0#")) return "0"; return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 

我得到一个例外,说它无法加载DataTemplate

这实际上是框架中的一个错误。 通过XmlnsDictionary添加本地名称空间将不起作用。 必须在模板定义中添加它,并定义程序集和命名空间:

如上面的评论@Nerd In Training这应该有效:

 string statRowTemplate = ""; private DataTemplate GenerateStatRowDataTemplate() { ParserContext pc = new ParserContext(); pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); pc.XmlnsDictionary.Add("xcdg", "http://schemas.xceed.com/wpf/xaml/datagrid"); string statRowTemplate = ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; statRowTemplate += ""; StringReader stringReader = new StringReader(statRowTemplate); XmlReader xmlReader = XmlReader.Create(stringReader); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(statRowTemplate.ToString())); DataTemplate dt = (DataTemplate)XamlReader.Load(ms,pc); dt.LoadContent(); return dt; }