DataTemplateSelector item is Null

230 Views Asked by At

This is similar issue to this, but the answer did not work for me.

I have a simple window with a ContentControl. I wanted to use a template selector with it.
I set up the binding for the Content and chose a ContentTemplateSelector (which is located in another file/namespace).

<Window x:Class="EpicNum.View.Floaters.FloaterDnD"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="57" Width="130"  
    WindowStyle="None" ResizeMode="NoResize" ShowInTaskbar="False">

    <ContentControl Content="{Binding}"
                    ContentTemplateSelector="{StaticResource NodeTemplateSelector}"
                    />
</Window>

My template selector class looks looks like this:

class NodeTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        FrameworkElement UIElement = container as FrameworkElement;

        // Add new information for new Node Template selections here...
        if (item.GetType() == typeof(ViewModel.NodeAdder))
        {
            return UIElement.FindResource("TemplateAdderNode") as DataTemplate;
        }
        else if (item.GetType() == typeof(ViewModel.NodeText))
        {
            return UIElement.FindResource("TemplateTextNode") as DataTemplate;
        }
        return base.SelectTemplate(item, container);
    }
}

Somewhere in the ViewModel, I create a new instance for this window and set the DataContext

FloaterDnD F = new FloaterDnD();
F.DataContext = sourceItem;
F.Show();

Now, for some reason the item in my template selector turns out null. I can't figure out, what am I missing.

At runtime, in code I can see that the DataContext is set correctly enter image description here

But, when it gets to the template selector, it's null enter image description here

Might be related.
For some reason, when I set the ContentTemplateSelector in xaml for the window, the UI designer shows an error:
enter image description here

If I remove the assignment for ContentTemplateSelector, then the error is gone and it shows the window as normal.

0

There are 0 best solutions below