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.
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?
Visual Studio 2017
I had exactly the same problem. It was compiling one day ... and then it wasn't. I wasn't using DependencyProperty which shouldn't be needed as above. The properties were appearing in Intellisense but gave the same message when inserted. I cleaned, built, rebuilt, restarted VS, rebooted etc. All to no avail.
Last ditch try ... I removed all the offending attributes and got a clean compile. Then I put them back and it compiled. I really wasn't expecting that. Somehow VS had gotten its knickers in a twist.
If you are using VS2017, try to delete bin and obj folders in all projects of your solution, clean the solution and build again. It works for me !
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With