views:

997

answers:

1

I am making a Silverlight UserControl where the consumer of the control needs to be able to provide custom attributes and content. I thought this would be as easy as exposing my custom attributes as dependency properties and deriving from ContentControl, but apparently not.

Here are my questions regarding this:

  1. I got the attribute to work as a simple dependency property, but to bind it to the UI in the control itself, I had to set the DataContext of the control to its own class (this.DataContext = this). This felt dirty all over...is there a better way to do this?

  2. I can get the consumer of my custom control to compile with a Content child element, but I don't know how to display this in the control itself. I was thinking that a ContentPresenter whose Content is bound to the Content in the current binding context, but that's not working.

I'd like to get this to work, but I'm also interested in what the recommended/best practice is and why. I had a tough time googling these things.

+3  A: 

Note: i have no experience in silverlight, but in WPF i'd do the following

Let's say you have a control MyControl which derives from UserControl, with a property MyProperty. I think the prettiest is to define a ControlTemplate for your control:

<UserControl.Template>
    <ControlTemplate TargetType="{x:Type SomeNamespace:MyControl}">
        <StackPanel>
            <TextBlock Text="{TemplateBinding MyProperty}"/>
            <ContentPresenter/>
        </StackPanel>
    </ControlTemplate>
</UserControl.Template>

With {TemplateBinding} you can quickly create (OneWay!) bindings to properties of your control, while you can still use the normal {Binding} syntax to bind to your actual DataContext. Placing a ContentPresenter in your ControlTemplate will automatically display whatever is in your Content Property.

Bubblewrap