繁体   English   中英

如何从 WPF 后面的代码创建带有 ItemsControl 的 DataTemplate

[英]How to create DataTemplate with ItemsControl from code behind WPF

我有一个带有一些常量 GridViewColumns 的自定义 ListView,我像这样在 XAML 中创建

<GridViewColumn Header="Name" Width="150">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding ListOfSubObjects}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical"></StackPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding SubObjectName}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

ListView 本身的 ItemSource 是一个对象列表,这些对象本身包含一个子对象列表 (ListOfSubObjects) 到我想要绑定显示文本的属性。

我想从后面的代码中动态添加具有相同结构的 GridViewColumns,但是我找不到将带有 ItemSource 的 ItemTemplate 添加到 DataTemplate 的方法。 我该怎么做?

您可以使用 FrameworkElementFactory 将数据模板添加到单元模板,并且此示例也适用于将数据模板添加到 ItemTemplate:

GridViewColumn gvc = new GridViewColumn();
DataTemplate dt = new DataTemplate();
FrameworkElementFactory fc = new FrameworkElementFactory(typeof(ItemsControl));
fc.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("ListOfSubObject"));
dt.VisualTree = fc;
gvc.CellTemplate = dt;

您可以使用XamlReader.Parse方法从 XAML 字符串动态创建元素:

const string Xaml = "<ItemsControl ItemsSource=\"{Binding ListOfSubObjects}\">" +
"                <ItemsControl.ItemsPanel>" +
"                    <ItemsPanelTemplate>" +
"                        <StackPanel Orientation=\"Vertical\"></StackPanel>" +
"                    </ItemsPanelTemplate>" +
"                </ItemsControl.ItemsPanel>" +
"                <ItemsControl.ItemTemplate>" +
"                    <DataTemplate>" +
"                        <TextBlock Text=\"{Binding SubObjectName}\"/>" +
"                    </DataTemplate>" +
"                </ItemsControl.ItemTemplate>" +
"            </ItemsControl>";

ParserContext parserContext = new ParserContext();
parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
parserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");

ItemsControl itemsControl = XamlReader.Parse(Xaml, parserContext) as ItemsControl;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM