为什么我在WPF用户控件上看到"成员无法识别或无法访问"错误?

soa*_*gem 18 c# wpf xaml

我有一个自定义用户控件,其中包含我希望能够在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已经扭曲了它的短裤.

  • 如果重建项目没有帮助。尝试将平台从AnyPC更改为x86或x64。这样可以解决问题。 (2认同)

小智 9

如果您使用的是VS2017,请尝试删除解决方案所有项目中的bin和obj文件夹,清理解决方案并重新生成。这个对我有用 !

  • 简单的解决方案构建对我来说很成功。 (3认同)

Moe*_*bai 8

您需要将您的财产声明为 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)

  • 非常感谢@MoezRebai!这非常有效.需要注意的一点是,在我包含此代码之后,我必须在错误消失之前再次构建项目. (3认同)

小智 7

将构建目标从AnyCPU更改为x86或x64。不确定为什么AnyCPU无法正常工作。