XAML中定义的DataTemplate具有空的VisualTree。

4

我正在使用.NET 3.0的WPF。

我定义了一个相对简单的DataTemplate作为GridView的CellTemplate。我期望DataTemplate的VisualTree属性包含FrameworkElementFactory,但是当我尝试从GridViewColumnHeader.Click事件中访问该属性时,该属性为空。为什么VisualTree为空?我需要访问它。这是ListView的定义:

<ListView ItemsSource="{Binding Stuff}" GridViewColumnHeader.Click="Header_Click">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="28">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Image Name="statusImage" Width="16" Height="16" Source="../Images/media_play_green_16x16.png"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

以下是事件处理程序:

private void Header_Click(object sender, RoutedEventArgs e)
{
    GridViewColumnHeader gvch = e.OriginalSource as GridViewColumnHeader;

    // error! VisualTree is null!
    //gvch.Column.CellTemplate.VisualTree.GetType(); 
}

你能告诉我们为什么需要访问模板的可视树吗?也许有更好的方法来实现你想做的事情...不过我很好奇为什么它是null,这真的很令人惊讶... - Thomas Levesque
简短的版本是,我想调用VisualTree.SetBinding(FrameworkElement.DataContextProperty,new Binding(“Item”));其目的是使单元格模板中的所有数据绑定都相对于ItemsSource中实际项目上的“Item”属性。 - atoumey
2个回答

7
这是已知且预期的行为。我现在找不到MSDN或其他“权威”的引用,但此MSDN论坛帖子解释了这一点(有点!):

FrameworkTemplate.VisualTree属性 ...主要用于在代码中以编程方式创建DataTemplate/ControlTemplate, 当使用XAML定义DataTemplate/ControlTemplate时,此属性将为空, 因为WPF使用另一种机制来实例化和构造XAML生成的模板(强调添加)

因此,当从XAML加载模板时,VisualTree属性不会填充:仅当您使用FrameworkElementFactory在代码中构建模板时才会填充。

要获取在XAML中定义的模板的内容,请调用FrameworkTemplate.LoadContent()。这将实例化模板并为您提供根元素 - 然后您可以根据需要进行钻取并设置属性或绑定。不过,将实例化的实例插入包含窗口或控件的可视树中取决于您,因此您可能希望封装它!


谢谢。您知道有哪些文章可以解释如何动态地将加载的模板插入到ItemsControl中吗?我想在GridViewColumnHeader的CellTemplate上调用LoadContent(),并将结果插入到ListView中的单元格中。 - atoumey
很抱歉,Atourney,我想不行。我以为我有一个旧项目的样本,但我再也找不到了,而且那在完全不同的任何地方。我的猜测是,您需要子类化ListView并覆盖GetContainerForItemOverride以返回ListViewItem的子类,然后将代码放入该ListViewItem的子类中--但我没有测试过这个方法。 - itowlson
谢谢。我已经为此打开了一个新问题:http://stackoverflow.com/questions/2553964/how-do-i-manually-manage-the-generation-of-cell-visuals-with-a-gridviewcolumn-cel - atoumey

0
Visual Tree 为空的原因是因为 Visual Tree 属性更接近于逻辑树而不是视觉树。模板的实际内容存储在 TemplateContent 对象中,该对象没有公共成员,您需要使用 LoadContent 方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接