views:

62

answers:

2

Hello, I am currently creating a few test controls. In WPF everything is fine, I can subclass e.g. Border or ScrollViewer. In Silverlight this is not possible, so I have to do a little trick (multi-targeting)...

I am deriving my test element from StackPanel and add the content as child. I could, of course, also derive from WrapPanel, Canvas....

My question is, when using this approach, which UI element in Silverlight (not sealed) is the best to use. It should interfere as little as possible with the test element. Or do I have to distiguish between elements (with width settings e.g.)..

Let me give a better example. If I want a simple TextBlock which always says "Hello" and has a red Background. In WPF, I subclass the TextBlock. This is not possible in Silverlight. There I would e.g. do this:

public class RedTextBlock : StackPanel
{
    public TextBlock WrappedBlock {get; private set;}
    public RedTextBlock()
    {
        WrappedBlock = new TextBlock
        {
            Text = "Hello",
            Background = new SolidColorBrush(Colors.Red)
        };

        Children.Add(WrappedBlock);
    }
}

I do not really like the solution, but have not found a better one. But in this case, I am not sure if the StackPanel is not way to smart for my example. Because I THINK it may influence the layout (e.g. taking as much space as possible) in opposition to a direct textblock instance.

In other cases the containing control may be a ScrollViewer, an Image, whatever.. All controls which I can't subclass "correctly" because they are sealed.

Is this approach OK, which control would be the best to subclass in this generic cases, or are there better ideas? (I do not want to go the "interface - View as Property" way, I really want to subclass existing UI element)..

Chris

A: 

If you want to stack things, then the StackPanel is fine. If you only have one child then your best bet would be to use ContentControl and set the TextBlock as the content. If you have lots of children you could use Panel, but if you go that route you have to manually lay out all the children. But for what you're describing I think the Content Control is best.

Bryant
A: 

Let me give a better example. If I want a simple TextBlock which always says "Hello" and has a red Background. In WPF, I subclass the TextBlock.

Rather than subclassing, have you considered using Styles instead? It is far more suitable for situations like this.

KeithMahoney
Yes, I am using them for some things, but most of the time I need far more complex things. Was just the most simple example, but thanks for the hint..
Christian