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

mnowg1ta  于 2022-12-16  发布在  其他
关注(0)|答案(8)|浏览(840)

我有一个自定义的用户控件,它有一个公共属性,我希望能够在XAML中设置它。

测试控件.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">

测试控制.xaml.cs

using System.Windows.Controls;

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

然后,在我的MainWindow.xaml文件中,我尝试包含以下内容:

<controls:TestControl TestMe="asdf" />

但是,即使Visual Studio自动完成TestMe属性,我还是会看到带有弯曲下划线的内容,显示“成员“Test Me”无法识别或无法访问,”如下所示。

我可以发誓我以前在其他项目中做过类似的事情。我如何像这样通过XAML访问(即设置)公共属性?

bmp9r5qi

bmp9r5qi1#

可视化工作室2017
我也遇到了同样的问题。有一天它正在编译......然后就没有了。我没有使用DependencyProperty,这是不应该像上面那样需要的。这些属性出现在Intellisense中,但插入时给出了相同的消息。我清理、构建、重建、重新启动VS、重新启动等等。所有这些都无济于事。
最后一次尝试......我删除了所有有问题的属性,得到了一个干净的编译。然后我把它们放回去,编译了它。我真的没有预料到这一点。不知何故,VS已经得到了它的内裤在扭曲。

vhmi4jdf

vhmi4jdf2#

如果你使用的是VS2017,试着删除你的解决方案中所有项目的bin和obj文件夹,清理解决方案并重新构建。

bn31dyow

bn31dyow3#

您需要将属性声明为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();
        }
    }
}
5kgi1eie

5kgi1eie4#

将构建目标从AnyCPU更改为x86或x64。不确定AnyCPU不工作的原因。

s4chpxco

s4chpxco5#

我知道这是晚了,但我刚刚遇到这个问题上VS 2020。
我尝试了上面列出的所有3个选项,没有一个工作,包括CPU构建。

我最终不得不右键单击每个项目,清理,并重建。然后它解决了这个问题...
真烦人,这仍然是一个问题。

8wtpewkr

8wtpewkr6#

在我的例子中,最初没有错误,在我修改我的类之后,在我的类中有一些错误,然后显示Xaml错误member is not recognized。在解决了我的类中的错误之后,我通过了构建项目,所有项目都被构建而没有错误,但是错误仍然显示在Error List Window中。最后,我重新启动Visual Studio,错误消失了。

628mspwn

628mspwn7#

我的VS2022遇到了这个问题,我只是删除了WindowsBase引用,它就起作用了。

fcg9iug3

fcg9iug38#

我将使用反射,而不是为控件设置多个依赖项属性。

public static readonly DependencyProperty UserControlProperty = DependencyProperty.Register("UserControl", 
typeof(object), typeof(CustomUserControl), new PropertyMetadata(null));

   public object UserControl
   {
            get { return GetValue(UserControlProperty); }
            set { SetValue(UserControlProperty, value); }
   }

相关问题