Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c# - Changing WPF StackPanel template

I am trying to create a custom style panel (StyledStackPanel) which is identical to regular StackPanel, that has a custom style. For example - if the style is simply to add an underline, by writing:

<StyledStackPanel>
    <!--User content goes here-->
</StyledStackPanel>

I would like to receive the same appearance as if I wrote:

<StackPanel>
    <!--User content goes here-->
</StackPanel>
<Border Height="1" BorderBrush="Blue"/>

If StackPanel was a Control, I could have replace the DataTemplate of that control. However, it inherits Panel which inherits FrameworkElement.
Is there a way to change the template of a StackPanel?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no way to set a ControlTemplate for a panel, but you have several options:

  1. Create a custom/user control that has the StackPanel as a child.

  2. Inherit from StackPanel and override OnRender to draw your custom style (you may also need to override MeasureOverride and ArrangeOverride to add a little space around the panel's children for your drawing.

  3. Inherit directly from Panel and override OnRender, MeasureCore and ArrangeCore - if you need to use the panel is a specific way and you don't need all of StackPanel's option this maybe the easiest way since the StackPanel layout algorithm is simple.

  4. Inherit from Decorator (if you do your drawing in code) or ContentControl (if you want to use ControlTemplate) and warp your panel with it when you use it:

         <l:PanelStyle>
             <StackPanel> .. <StackPanel>
         </l:PanelStyle>
    
  5. Write the style for ItemsControl, ItemsControl has a ControlTemplate that you can set and basically wraps a panel (by default it's a vertical StackPanel).

I would go with option 4 if you need access to the StackPanel's properties or 5 if you don't.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...