I'm trying to build a ContentControl
-derived control (let's call it MyContentControl
) that will have its ControlTemplate
set by an instance of a DataTemplateSelector
-derived type (let's call it MyTemplateSelector
).
When I try to this:
ContentControl contentControl = new ContentControl();
contentControl.ContentTemplateSelector = new MyTemplateSelector();
contentControl.Content = "Some ContentControl Content";
MyContentControl myContentControl = new MyContentControl();
myContentControl.ContentTemplateSelector = new MyTemplateSelector();
myContentControl.Content = "Some MyControl Content";
I expect that, when I set content on those controls, MyTemplateSelector
's override of DataTemplateSelector.SelectTemplate()
method gets called for both contentControl
and myContentControl
.
In reality, it gets called only for contentControl. What do I need to do (and why!) to make it work for myContentControl
too?
(Not sure if it's relevant, but for the moment MyContentControl
does not do anything with DependencyProperties
other than overriding metadata information for DefaultStyleKeyProperty
.
EDIT (moved content from other post to original question):
Here is a bit more elaborated example:
Create MyContentControl:
public class MyContentControl : ContentControl { static MyContentControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof (MyContentControl), new FrameworkPropertyMetadata(typeof (MyContentControl))); } public MyContentControl() {} }
Create
MyTemplateSelector
:public class MyTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { return null; // <== Place the breakpoint here } }
Add
ContentControl
andMyContent
control to your main window (for example):<StackPanel> <local:MyContentControl x:Name="myContentControl" /> <ContentControl x:Name="contentControl" /> </StackPanel>
Add this code somewhere after
InitializeComponent
(or inLoaded
handler):myContentControl.ContentTemplateSelector = new MyTemplateSelector(); myContentControl.Content = "123"; contentControl.ContentTemplateSelector = new MyTemplateSelector(); contentControl.Content = "ABC";
The breakpoint mentioned in step (2) gets hit only once, for content="ABC"
and contentControl
element.