我有一个自定义用户控件,其中包含我希望能够在XAML中设置的公共属性.它在下面.
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">
Run Code Online (Sandbox Code Playgroud)
TestControl.xaml.cs
using System.Windows.Controls;
namespace MyProject.Controls
{
public partial class TestControl : UserControl
{
public string TestMe { get; set; }
public TestControl()
{
InitializeComponent();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的MainWindow.xaml文件中,我尝试包含这个:
<controls:TestControl TestMe="asdf" />
Run Code Online (Sandbox Code Playgroud)
但是,即使Visual Studio自动填充了TestMe属性,我也会看到带有波浪线下划线的内容,表示"成员"测试我"无法识别或无法访问",如下所示.

我可以发誓我之前在其他项目中做过类似的事情.如何通过XAML访问(即设置)公共属性?
Pau*_*ous 22
Visual Studio 2017
我有完全相同的问题.它有一天正在编译......然而事实并非如此.我没有使用上面不需要的DependencyProperty.属性出现在Intellisense中,但在插入时给出相同的消息.我清理,建造,重建,重新启动VS,重新启动等等都无济于事.
最后一次尝试...我删除了所有违规的属性并得到了一个干净的编译.然后我把它们放回去编译.我真的没想到.不知怎的,VS已经扭曲了它的短裤.
您需要将您的财产声明为 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)