jackbot
jackbot

Reputation: 3021

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="SomeDataTemplate" 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

Upvotes: 1

Views: 1751

Answers (1)

brunnerh
brunnerh

Reputation: 184396

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

Upvotes: 2

Related Questions