繁体   English   中英

如何在XAML WPF中访问自定义控件的属性

[英]how to access property of a custom control in XAML WPF

我有一个带有Text属性的自定义MyButton

public string Text
{
    get { return aTextBlockInButton.Text; }
    set { aTextBlockInButton.Text = value; }
}

在C#中创建按钮并设置其Text属性有效(文本显示正确):

MyButton b = new MyButton(); 
b.Text="hello";

但是,当我在XAML中执行此操作时

<local:MyButton Text="someText" />

我得到错误

the member "Text" is not recognized or is not accessible. 

为什么? 请注意, MyButton显示在Intellisense中。

XAML编辑器实际上是错误的。 有时它不能正确报告并给出错误的错误通知。 因此,您不应该始终相信XAML编辑器会告诉您什么。 我什至有一个很长的XAML代码,但是报告了整个代码,但XAML编辑器内部存在一些问题,但是无论如何都可以运行/调试该代码。 因此,我的建议是首先相信自己,如果有任何实际错误,您将无法编译和运行它。

有时,在运行代码后,回到XAML代码,您会看到错误通知已消失。

您需要一个依赖项属性,普通属性无法在XAML绑定上使用。

像这样的东西

public static readonly DependencyProperty TextProperty = 
DependencyProperty.Register("Text", typeof(string), typeof(Button));
public string Text
{
    get
    {
        return this.GetValue(TextProperty) as string;
    }
    set
    {
        this.SetValue(TextProperty, value);
    }
}

在此处阅读有关依赖属性的更多信息: 依赖属性教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM