【问题标题】:Accessing a datatemplate control in WPF programmatically以编程方式访问 WPF 中的数据模板控件
【发布时间】:2011-03-24 10:35:55
【问题描述】:

在我的 WPF 应用程序中,我有一个 DocumentViewers 列表,它们绑定到对象的某些属性。我将对象添加到 ListBox 并以编程方式应用将对象的属性绑定到 DocumentViewer 的数据模板。这意味着 DocumentViewer 根本没有在代码中声明,但我想稍后更改属性。我怎样才能做到这一点?我的代码如下所示:

<DataTemplate x:Key="SomeDataTemplate" x:Name="DocumentViewerTempl">
    <DocumentViewer x:Name="DocV" Document="{Binding DocumentContent}"
                    Style="{StaticResource DocumentViewerStyle1}"/>
</DataTemplate>

文档的内容在Document 类的DocumentContent 属性中,如您所见,绑定发生在上面。我的问题是如何在代码中访问 DocumentViewer?我试过给它一个名字并引用它,但这显然不是这样做的方法......

谢谢

【问题讨论】:

    标签: c# wpf xaml data-binding listbox


    【解决方案1】:

    您可以通过ItemContainerGenerator

    var itemContainer = 
        listBox.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem;
    
    // or: 
    var itemContainer = 
        listBox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
    
    var viewer = 
        itemContainer.ContentTemplate.FindName("DocV", itemContainer) as DocumentViewer;
    
    // Do stuff with viewer
    

    【讨论】:

      猜你喜欢
      • 2011-10-19
      • 2015-12-09
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多