开发者

How to resolve ContentControl ContentTemplateSelector on designtime?

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.MainWindow being null at design time. Here's a better way to retrieve the resource by name:

public override DataTemplate SelectTemplate( object item, DependencyObject container ) {
    var element = container as FrameworkElement;
    if ( element != null ) {
        var template = element.TryFindResource( "Temp1" ) as DataTemplate;
        if ( template != null ) {
            return template;
        }
    }
    return base.SelectTemplate( item, container );
}

Other parts of your code are still incomplete, though, so I hope you're just in the middle of it. Your DataTemplate should have bindings, for example, rather than hard-coded values.


I suspect Application.Current.MainWindow is not set at design time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜