开发者

Accessing a datatemplate control in WPF programmatically

In my WPF application I have a list of DocumentViewers which are bound to some property of an object. I add the object to a ListBox and programmatically apply a datatemplate which binds the property of the object to the DocumentViewer. This means the DocumentViewer isn't declared at all in the code, but I want to get at it to change a property later on. How can I do this? My code looks like the following:

<DataTemplate x:Key="SomeDataTempla开发者_运维知识库te" x:Name="DocumentViewerTempl">
    <DocumentViewer x:Name="DocV" Document="{Binding DocumentContent}"
                    Style="{StaticResource DocumentViewerStyle1}"/>
</DataTemplate>

The contents of the document are in the DocumentContent property of the Document class, so as you can see, the binding takes place above. My question is how to access the DocumentViewer in the code? I've tried giving it a name and referencing that but that's clearly not the way to do it...

Thanks


You can do this via the 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜