为什么我看到“成员无法识别或无法访问"?我的 WPF 用户控件出错? [英] Why am I seeing a "member is not recognized or is not accessible" error on my WPF User Control?

查看:175
本文介绍了为什么我看到“成员无法识别或无法访问"?我的 WPF 用户控件出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义用户控件,其中包含一个我希望能够在 XAML 中设置的公共属性.就在下面.

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();
        }
    }
}

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

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

<controls:TestControl TestMe="asdf" />

但是,即使 Visual Studio 自动完成 TestMe 属性,我也会看到带有波浪线下划线的内容,上面写着成员Test Me"无法识别或无法访问,如下所示.

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.

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

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?

推荐答案

您需要将您的属性声明为 Dependency Properties

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();
        }
    }
}

这篇关于为什么我看到“成员无法识别或无法访问"?我的 WPF 用户控件出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆