WPF - Get DataTemplate without an event

2019-08-12 00:11发布

问题:

I have a WPF Data template defined in my Windows.Resources section.

I would like to access this (really a list box on it) via the code behind. How can I do this?

I can't get what I want via an event because I want to get the reference in the completed step of a BackGroundWorker. (Ie no sender (that is a UI element) to go off of there).

How can I get a reference to this?

I have tried:

myContainingPanel.Template.Find("lstBox", myContainingPanel);

and (Taken from here):

ContentPresenter contentPresenter = myContainingPanel.FindVisualChild<ContentPresenter>();
DataTemplate template = contentPresenter.ContentTemplate;
return (T) template.FindName(name, contentPresenter);

I would accept an answer that says I should use MVVM if there is an good example showing how that would work (with a backgroundworker completed event).

Thanks for any help

回答1:

FrameworkElement.FindResource() should work. Finding data templates from viewmodel doesn't seem right to me. What are you trying to do?