Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify which Property goes between the opening and closing tag in Xaml

Consider the following Xaml

<Grid>
    <TextBox>Text</TextBox>
    <Button>Content</Button>
</Grid>

It will set the

  • Text Property of a TextBox (only WPF)
  • Content Property of a Button
  • Children Property of a Grid

But how is this specified? How do you specify which Property that goes between the opening and closing tag in Xaml?
Is this set by some metadata in the Dependency Property or what?

Thanks

like image 821
Fredrik Hedblad Avatar asked Jan 07 '11 20:01

Fredrik Hedblad


1 Answers

There is a ContentPropertyAttribute that is applied to a class. WPF/Silverlight will use reflection to determine which property to use.

If you want to do this with a custom class, you can do it like so:

[ContentProperty("Bar")]
public class Foo : Control
{
    public static DependencyProperty BarProperty = DependencyProperty.Register(
        "Bar",
        typeof(int),
        typeof(Foo),
        new FrameworkPropertyMetaData(0));

    public int Bar
    {
        get { return (int)GetValue(BarProperty); }
        set { SetValue(BarProperty, value); }
    }
}

Then you could specify it in XAML like so:

<lcl:Foo>12</lcl:Foo>

Update

Since it is using reflection, you don't really need to do a DependencyProperty. For instance, this will also work:

[ContentProperty("Bar")]
public class Foo : Control
{
    public int Bar { get; set; }
}   
like image 97
Abe Heidebrecht Avatar answered Oct 04 '22 19:10

Abe Heidebrecht