Why I can’t resolve ContentControl ContentTemplateSelector on designtime?
(On run time it works)
Designer (VS2010) shows an exception:
System.Reflection.TargetInvocationException
Exception has been thrown by the
target of an invocation.
and
System.NullReferenceException Object
reference not set to an instance of an
object.
XAML:
<Window.Resources>
<DataTemplate x:Key="Temp1">
<TextBox TextWrapping="Wrap" Text="1" Height="20" Width="Auto"/>
</DataTemplate>
<local:TemplateSelector x:Key="mySelector"/>
<Grid>
<ContentControl ContentTemplateSelector="{StaticResource mySelector}">
<ContentControl.Content>
1
</ContentControl.Content>
</ContentControl>
</Grid>
</Window.Resources>
C#:
public class TemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
//int num = int.Parse(item.ToString());
Window win = Application.Current.MainWindow;
return win.FindResource("Temp1") as DataTemplate;//load template based on num...
}
}
H.B. is right about
Application.Current.MainWindowbeingnullat design time. Here’s a better way to retrieve the resource by name:Other parts of your code are still incomplete, though, so I hope you’re just in the middle of it. Your
DataTemplateshould have bindings, for example, rather than hard-coded values.