简体   繁体   English

从xaml wp8创建c#类的实例

[英]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. 假设我想创建一个具有Image和2 ImageSource属性的ImageButton类,然后在.xaml文件中创建ImageButton的实例,以便可以根据需要的布局放置它。

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 我已经尝试在任何类之外的正确项目命名空间中创建类,使用空参数声明构造函数,然后在添加的xaml中

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 但是据说不能分配给集合,预期类型的​​UIElement和类型“ ImageButton”不包含任何可访问的构造函数

is there is a way to reference ac# class and create an instance in wp8 xaml ? 有没有一种方法可以引用ac#类并在wp8 xaml中创建实例? or is it not possible ? 还是不可能?

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) 如果希望您的类成为UI的一部分,则需要派生自UIElement类的子类之一(基本上是任何控件)

According to the MSDN , the UIElement class shouldn't be directly inherited: 根据MSDN ,UIElement类不应直接继承:

UIElement does not expose a public constructor. UIElement不公开公共构造函数。
Typically, you don't derive classes from either UIElement or FrameworkElement directly. 通常,您不会直接从UIElement或FrameworkElement派生类。 More typically used base classes for derived custom classes are these classes: 这些类通常用于派生的自定义类,这些类是:
- Specific controls that are not sealed (for example, TextBox) -未密封的特定控件(例如,TextBox)
- Control base classes (Control, ContentControl, UserControl) -控件基类(Control,ContentControl,UserControl)
- Navigation elements (Page, Frame) -导航元素(页面,框架)
- Panel classes (the base class Panel, or specific non-sealed implementations such as Grid) -Panel类(Panel类的基类,或特定的非密封实现,例如Grid)

In your case, I guess a Button would be the most appropriate class to inherit. 就您而言,我想一个Button将是最合适的继承类。

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. 此外,如果要创建自定义控件,还需要记住一个视觉方面-扩展基本控件的模板可能是一个不错的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM