A lightweight templateable WPF shape

谁都会走 提交于 2019-12-07 17:47:16

问题


I'm using ellipses and other shapes as onscreen markers, I would like others to be able to change these visuals using templates. However, as shape doesn't support templating I'm forced to create a basic UserControl, which defaults to show an ellipse, and then use that instead of the basic shape.

Has anyone got a neater solution? I'm a little concerned if I create 1000's of these onscreen that performance/memory will be a bit of an overhead.


回答1:


UserControl derives from ContentControl. It doesn't sounds as though you need content (the ability to host additional controls inside your shape), so I'd keep going up the hierarchy...

Here's a breakdown of the ancestry:

UserControl
    ContentControl
        Control
            FrameworkElement
                UIElement
                    Visual
                        ...

Control defines the Template property, so I think the lightest means of achieving what you want is to use Control:

<Control Style="{StaticResource MyStyle}"/>

...and use a Style to set the template and any triggers/etc that you need.

If however you do need to host a child element inside your shape, you should use ContentControl thus:

<ContentControl Style="{StaticResource MyStyle}"/>

If you find that this approach is too heavy-weight at runtime, then you might consider using Shape.

Shape
    FrameworkElement
        UIElement
            Visual
                ...

Shape does not inherit from Control, but rather directly from FrameworkElement. It is not templateable. It's an abstract class, of which you'd need to create your own custom subclass that knows how to describe its own presentation via the DefiningGeometry property. This might be more complex than defining a style on a Control, but if you need the extra performance then you may have to go this route.

EDIT You might like to check out DrawingVisual as well. From MSDN:

The DrawingVisual is a lightweight drawing class that is used to render shapes, images, or text. This class is considered lightweight because it does not provide layout or event handling, which improves its performance.

It also is not templateable, but if you need raw performance then it's worth a look.



来源:https://stackoverflow.com/questions/564404/a-lightweight-templateable-wpf-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!