Wednesday, February 3, 2016

Adding x:Name to a user control causes a compilation error

I was developing a new user control and realized I wanted to bind to a dependency property. The XAML looks like this.

<UserControl x:Class="FileInputBox.FileInputBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DockPanel>
        <Button x:Name="theButton" DockPanel.Dock="Right" Click="theButton_Click">Browse...</Button>
        <TextBox x:Name="theTextBox" MinWidth="{Binding ActualWidth, ElementName=theButton}" Margin="0,0,2,0"/>
    </DockPanel>
</UserControl>

I want to bind the text property of the TextBox to a dependency property of the UserControl called FileName. So I gave the UserControl a name and bound to it so the XAML looks like this.

<UserControl x:Class="FileInputBox.FileInputBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Name="root">
    <DockPanel>
        <Button x:Name="theButton" DockPanel.Dock="Right" Click="theButton_Click">Browse...</Button>
        <TextBox x:Name="theTextBox" MinWidth="{Binding ActualWidth, ElementName=theButton}" Margin="0,0,2,0" Text="{Binding Path=FileName, ElementName=root}"/>
    </DockPanel>
</UserControl>

Now I get a compilation error...
The type name 'FileInputBox' does not exist in the type 'FileInputBox.FileInputBox'

It turns out the problem is that the Namespace and the Class names are the same. All I had to do is rename the Class. The problem occurs as the compiler tries to figure out exactly what is being called "root". Seems odd to me.

No comments:

Post a Comment