otong
otong

Reputation: 1545

create instance of c# class from xaml wp8

suppose i want to create an ImageButton class that has an Image and 2 ImageSource attribute then create instance of ImageButton in .xaml file, so that I can place it according to my desired layout.

I already tried creating the class in the correct project namespace outside any classes, declare constructor with an empty argument, then in the xaml I added

xmlns:local="clr-namespace:projectNameSpace"
...
<m:ImageButton></ImageButton>

It is not working, then tried other code,

xmlns:m="clr-namespace:projectNameSpace"
...
<m:ImageButton></ImageButton>

but it is said that cannot assigned to the collection, expected type UIElement and the type "ImageButton" does not include any accessible constructor

is there is a way to reference a c# class and create an instance in wp8 xaml ? or is it not possible ?

Upvotes: 0

Views: 79

Answers (1)

Arkadiusz Szechlicki
Arkadiusz Szechlicki

Reputation: 66

If you want your class to be part of the UI, you need to derive from one of the subclasses of the UIElement class (basically, any control)

According to the MSDN, the UIElement class shouldn't be directly inherited:

UIElement does not expose a public constructor.
Typically, you don't derive classes from either UIElement or FrameworkElement directly. More typically used base classes for derived custom classes are these classes:
- Specific controls that are not sealed (for example, TextBox)
- Control base classes (Control, ContentControl, UserControl)
- Navigation elements (Page, Frame)
- Panel classes (the base class Panel, or specific non-sealed implementations such as Grid)

In your case, I guess a Button would be the most appropriate class to inherit.

Furthermore, if you want to create a custom control, you need to remember about a visual aspect as well - extending a template of the base control can be a good starting point.

Upvotes: 1

Related Questions