Reputation: 2315
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?
Upvotes: 0
Views: 351
Reputation: 19895
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 Visual
class. Dont forget to override all the virtual methods from the Visual
class 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 UIElement
class. Here you can render it by overriding a virtual method of the UIElement
class called OnRender()
. This method receives a DrawingContext
parameter that can draw shapes as you like. Adorner
s work like this usually.
If you want properties such as Style
, DataContext
and Tag
etc, you may have to inherit from FrameworkElement
.
If you want your visual object to contain another Visual
object inside it then it can inherit from FrameworkContentElement
.
Upvotes: 1
Reputation: 17083
You could use a DataTemplate
to represent your data object:
<DataTemplate DataType="{x:Type local:yourObject}">
... your visuals
</DataTemplate>
Upvotes: 0