Search code examples
c#wpfxaml

Why am I seeing a "member is not recognized or is not accessible" error on my WPF User Control?


I've got a custom user control with a public property that I'd like to be able to set in XAML. Here it is below.

TestControl.xaml

<UserControl x:Class="Scale.Controls.TestControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">

TestControl.xaml.cs

using System.Windows.Controls;

namespace MyProject.Controls
{
    public partial class TestControl : UserControl
    {
        public string TestMe { get; set; }
        public TestControl()
        {
            InitializeComponent();
        }
    }
}

Then, in my MainWindow.xaml file, I try to include this:

<controls:TestControl TestMe="asdf" />

However, even though Visual Studio autocompletes the TestMe property, I then see things with a squiggly underline that says "The member "Test Me" is not recognized or is not accessible," as seen below.

The member "Test Me" is not recognized or is not accessible

I could have sworn I've done something like this before in other projects. How can I access (i.e. set) the public properties via XAML like this?


Solution

  • You need to declare your property as Dependency Properties

    namespace MyProject.Controls
    {
        public partial class TestControl : UserControl
        {
            //Register Dependency Property
    
            public static readonly DependencyProperty TestMeDependency = DependencyProperty.Register("MyProperty", typeof(string), typeof(TestControl));
    
            public string MyCar
            {
                get
                {
    
                    return (string)GetValue(TestMeDependency);
    
                }
                set
                {
                    SetValue(TestMeDependency, value);
                }
            }
    
            public TestControl()
            {
                InitializeComponent();
            }
        }
    }