我必须通过代码创建DataTemplate
。这是我的代码:
public DataTemplate getTemplate(int r)
{
string xaml = "<DataTemplate> " +
" <ListView Margin=\"0\" x:Name=\"lv0\" ItemTemplateSelector=\"{StaticResource MyTemplateSelector}\" MinWidth=\"50\" MinHeight=\"20\" ScrollViewer.VerticalScrollBarVisibility=\"Hidden\" BorderBrush=\"{x:Null}\" BorderThickness=\".2\" ScrollViewer.HorizontalScrollBarVisibility=\"Hidden\" HorizontalAlignment=\"Stretch\" Width=\"Auto\" ItemsSource=\"{Binding Events_" + r + "}\" Foreground=\"{x:Null}\" Background=\"{x:Null}\">" +
" <ListView.ItemContainerStyle>" +
" <Style TargetType=\"ListViewItem\">" +
" <Setter Property=\"Padding\" Value=\"0\"/>" +
" <Setter Property=\"HorizontalContentAlignment\" Value=\"Stretch\" />" +
" </Style>" +
"</ListView.ItemContainerStyle>" +
"<ListView.ItemsPanel>" +
" <ItemsPanelTemplate>" +
" <VirtualizingStackPanel" +
" Orientation=\"Horizontal\"" +
" IsItemsHost=\"True\"/>" +
" </ItemsPanelTemplate>" +
" </ListView.ItemsPanel>" +
" </ListView>" +
" </DataTemplate>";
MemoryStream sr = null;
ParserContext pc = null;
sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml));
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");
DataTemplate datatemplate = (DataTemplate)XamlReader.Load(sr, pc);
return datatemplate;
}
DataTemplate
返回就好了。但是如果你注意到我上面的XAML,你可以看到我在DataTemplateSelector
内也使用了ListView
。在我的XAML中,有一个选择器:
<Window.Resources>
<local:TaskListDataTemplateSelector x:Key="MyTemplateSelector"/>
</Window.Resources>
当我运行代码时,我的DataTemplate
返回正常。但是当它试图运行时,它找不到名为MyTemplateSelector
的资源。当我在代码中看到ResourceDictionary
时,我看到选择器的索引低于DataTemplate
集合中ResourceDictionary
s的索引。因此,我认为我的DataTemplate
正在尝试查找MyTemplateSelector
但无法查找,因为它存储在集合的下方。
我在这里做错了什么?有什么建议吗?