我想加载一个DataTemplate在代码隐藏,但它工作正常,如果我删除转换器...但只要我把它放在那里,它吹。现在,我确实将我的状态设置为我的名称空间,并将引用放置在XAML中的转换器中。例如:DataTemplate与转换器代码后
<Window.Resources>
<local:StatCellConverter x:Key="myConverter" />
</Window.Resources>
,这是我的方法,我产生一个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 = "<DataTemplate><xcdg:StatRow>";
statRowTemplate += "<xcdg:StatCell FieldName=\"Column4\" ResultPropertyName=\"AvgColumn4\">";
statRowTemplate += "<xcdg:StatCell.ContentTemplate>";
statRowTemplate += "<DataTemplate>";
statRowTemplate += "<TextBlock Text=\"{Binding ., Converter={StaticResource ResourceKey=myConverter}}\" />";
statRowTemplate += "</DataTemplate>";
statRowTemplate += "</xcdg:StatCell.ContentTemplate>";
statRowTemplate += "</xcdg:StatCell>";
statRowTemplate += "</xcdg:StatRow>";
statRowTemplate += "</DataTemplate>";
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
请发表您的转换器和定义“它吹“ – Paparazzi
我编辑的问题 –
我想通了。我不得不把资源设置在后面的代码... 串statRowTemplate = “”; statRowTemplate + =“ DataTemplate.Resources>”; –