Posts Tagged ‘ DataTemplate ’

The type reference cannot find a public type named ‘MyType’

Today I had a strange problem when I wanted to define a DataTemplate of a specific type which is located in the same assembly as I wanted to use it.
The problem was that if I wrote the assembly-name in the import of the Namespace then I got the following Exception:

The type reference cannot find a public type named ‘MyType’

So after a few hours of testing and searching I finally found the solution. I just had to remove the assembly from the import of the namespace.

Now lets have a look at a simple demonstration of the problem

This is the type I want to assign to the DataTemplate

namespace MyWpfApp
{
    public class MyType
    {
        private string _description;

        public MyType(string description)
        {
            _description= description;
        }

        public string Description
        {
            get { return _description; }
        }
    }
}

In the UI I defined a DataTemplate for this type

<Window x:Class="MyWpfApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:me="clr-namespace:MyWpfApp;assembly=MyWpfApp"
    Title="MainWindow">    
    <Window.Resources>
        <DataTemplate DataType="{x:Type me:MyType}"> <!-- Here it displays the error message -->
            <StackPanel Orientation="Vertical">
                <TextBlock Text="Description" FontWeight="Bold" Margin="5"/>
                <TextBlock Text="{Binding Description}" Margin="5"/>
            </StackPanel>
        </DataTemplate>
......

This code results in the error message I talked about before.

But if you change the import of the MyWpfApp namespace then it works without problems.

<Window x:Class="MyWpfApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:me="clr-namespace:MyWpfApp" <!-- REMOVED the assembly in the namespace import to fix the problem -->
    Title="MainWindow">    
    <Window.Resources>
        <DataTemplate DataType="{x:Type me:MyType}">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="Description" FontWeight="Bold" Margin="5"/>
                <TextBlock Text="{Binding Description}" Margin="5"/>
            </StackPanel>
        </DataTemplate>
......

Have fun

Advertisements