首先我要帮大家引入一个对象 他位置与 System.Windows.Markup; 命名空间下. 这里有一个静态类XamlReader,以及read方法 我们就要用他来创建我们的usercontrol.
了解这个对象后给大家一个实例看看怎么用吧~ 还是很简单的,
1. 我们创建一个类 自然就是我们的 usercontrol 了 继承自 control
2. 我们要把我们模板的 Xmal 以string 的形式保存写入程序中
3. 我们要在构造函数中载入这些 XAML
4. 我们在重载onapplytemplate() 方法中声明创建的对象XMAL代码.
以下是我要写入的Xaml;
构造函数
重载onapplytemplate
CODE:
// Summary:
// Provides a XAML processor engine for parsing XAML and creating corresponding
// Silverlight object trees.
public static class XamlReader
{
// Summary:
// Parses a well-formed XAML fragment and creates a corresponding Silverlight
// object tree, and returns the root of the object tree.
//
// Parameters:
// xaml:
// A string that contains a valid XAML fragment.
//
// Returns:
// The root object of the Silverlight object tree.
public static object Load(string xaml);
// Provides a XAML processor engine for parsing XAML and creating corresponding
// Silverlight object trees.
public static class XamlReader
{
// Summary:
// Parses a well-formed XAML fragment and creates a corresponding Silverlight
// object tree, and returns the root of the object tree.
//
// Parameters:
// xaml:
// A string that contains a valid XAML fragment.
//
// Returns:
// The root object of the Silverlight object tree.
public static object Load(string xaml);
了解这个对象后给大家一个实例看看怎么用吧~ 还是很简单的,
1. 我们创建一个类 自然就是我们的 usercontrol 了 继承自 control
2. 我们要把我们模板的 Xmal 以string 的形式保存写入程序中
3. 我们要在构造函数中载入这些 XAML
4. 我们在重载onapplytemplate() 方法中声明创建的对象XMAL代码.
以下是我要写入的Xaml;
CODE:
public class MyImage : Control
{
Image _myImage = null;
private const string _contentTemplate
= "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
"xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" +
"<Image x:Name=\"sonicImage\" Source=\"space.jpg\"></Image>" +
"</ControlTemplate>";
}
{
Image _myImage = null;
private const string _contentTemplate
= "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
"xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" +
"<Image x:Name=\"sonicImage\" Source=\"space.jpg\"></Image>" +
"</ControlTemplate>";
}
构造函数
CODE:
public MyImage()
{
Template = (ControlTemplate)XamlReader.Load(_contentTemplate);
ApplyTemplate();
}
{
Template = (ControlTemplate)XamlReader.Load(_contentTemplate);
ApplyTemplate();
}
重载onapplytemplate
CODE:
public override void OnApplyTemplate()
{
_myImage = (Image)GetTemplateChild("sonicImage");
}
{
_myImage = (Image)GetTemplateChild("sonicImage");
}

添加至收藏夹