I am wondering how to represent an object visually in WPF? For example I have a class which has a shape as a filed/property with which I want to represent the object when I add it to a panel, like a canvas for example. I know I can inherit from Shape and override the defining geometry property, but I was wondering if there was any other way?
Share
There are various ways to do this…
If your element does not render anything, but just sits in the visual tree (for some peculier reason), then to host it in visual tree you will have to inherit it from the
Visualclass. Dont forget to override all the virtual methods from theVisualclass to your benefit when you inherit.If it needs to render on the UI (which I guess is your requirement) then it has to inherit from
UIElementclass. Here you can render it by overriding a virtual method of theUIElementclass calledOnRender(). This method receives aDrawingContextparameter that can draw shapes as you like.Adorners work like this usually.If you want properties such as
Style,DataContextandTagetc, you may have to inherit fromFrameworkElement.If you want your visual object to contain another
Visualobject inside it then it can inherit fromFrameworkContentElement.