S
S
slavkin2016-08-24 12:11:56
WPF
slavkin, 2016-08-24 12:11:56

How in WPF, when creating your own component (for example, a button), add content on top of the existing one (for example, a frame)?

Hello! I'm trying to figure out how to write my own controls in WPF. And I had the following question: is it possible to somehow overlay any new content on top of the old one? I understand that Button already has its own Border, but this question is purely academic and is provided as an example.

class CustomButton : Button
{
  private readonly Border _border;
  private readonly VisualCollection _visualChildren;

  protected override Size ArrangeOverride(Size finalSize)
  {
    _border.Arrange(new Rect(0, 0, 100, 100));

    return finalSize;
  }

  protected override Int32 VisualChildrenCount => _visualChildren.Count;
  protected override Visual GetVisualChild(Int32 index) => _visualChildren[index];

  public CustomButton()
  {
    _visualChildren = new VisualCollection(this);

    _border = new Border();
    _border.BorderThickness = new Thickness(2);
    _border.BorderBrush = Brushes.Green;

    _visualChildren.Add(_bottomRight);
  }
}

For example, how can I make the border in this example draw on top of the Content of the Button base class? It is clear that I am overriding the visual tree here, but can I somehow add to it what is in the base class?
I tried calling the base.AddVisualChild method on the base class, hoping that my element would be added to the Button's visual tree, but that didn't work either:
class CustomButton : Button
{
  private readonly Border _border;

  protected override Size ArrangeOverride(Size finalSize)
  {
    _border.Arrange(new Rect(0, 0, 100, 100));

    return finalSize;
  }

  public CustomButton()
  {
    _border = new Border();
    _border.BorderThickness = new Thickness(2);
    _border.BorderBrush = Brushes.Green;
    base.AddVisualChild(_border);
  }
}

Thanks in advance!
PS: is there any documentation on these issues and, specifically, on the development of custom components for WPF? It is clear that MSDN in the first place, I will be happy with links to it, maybe I'm just not looking for it?
PPS: I understand that what I want to do here can be done through a template, but it is the programmatic approach that interests me.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Blake, 2016-08-24
@kyleabrock

I was also tormented by these questions. The simplest thing is to create an element in Blend by right-clicking - Edit Template->Current Template. Blend will generate XAML for the current element. And already in it you can do whatever your heart desires. Either by code or visually

L
Larry Underwood, 2016-09-01
@Hydro

Canvas will save you, won't it? Put a button inside the Canvas and draw a frame on top

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question