I have a custom MyButton
with a Text
property:
public string Text
{
get { return aTextBlockInButton.Text; }
set { aTextBlockInButton.Text = value; }
}
Creating a button in C# and setting its Text
property works (Text shows up correctly):
MyButton b = new MyButton();
b.Text="hello";
However, when I do this in XAML
<local:MyButton Text="someText" />
I get the error
the member "Text" is not recognized or is not accessible.
Why? Note that MyButton
shows up in Intellisense.
The XAML editor is actually buggy. Sometimes it does not report correctly and gives incorrect error notification. So you should not always believe in what XAML editor tells you. I even had a very long XAML code but the whole code was reported with some problem inside XAML editor, however running/debugging the code anyway is OK. So my advice is believe in yourself first, if there is any actual error, you won't be able to compile and run it.
Sometimes after running the code, coming back to the XAML code, you'll see the error notification has gone away.
You need a dependency property, normal properties wont work on XAML binding.
something like this
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);
}
}
read more about dependency property here: Dependency Property Tutorial
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.