
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//Silverligh2 提供 XamlReader.Load(string xaml) 片段式 创建xaml。
//命名空间"http://schemas.microsoft.com/client/2007" 不能少。
string buttonXAML = "<Button xmlns='http://schemas.microsoft.com/client/2007' Width=\"60\" Height=\"50\" Content=\"string\" Margin=\"10\" Foreground=\"Red\"></Button>";
Button btnRed = (Button)System.Windows.Markup.XamlReader.Load(buttonXAML);
sp.Children.Add(btnRed);
//从文件创建,该文件 的Build Action 为 "Page", 与"Resource"类似,被嵌入程序集内
Button btn1 = (Button)LoadXaml("/LoadXaml;component/btns/btn1.xaml");
sp.Children.Add(btn1);
//从文件创建,该文件 的Build Action 为 "Resource",被嵌入程序集内
//注意格式:"/命名空间;component/文件位置"
Button btn2 = (Button)LoadXaml("/LoadXaml;component/btns/btn2.xaml");
sp.Children.Add(btn2);
//从文件创建,该文件 的Build Action 为 "Content",仅打包进.xap中,不在任何程序集内
Button btn3 = (Button)LoadXaml("btns/btn3.xaml");
sp.Children.Add(btn3);
//从错误的文件创建,最终生成的是默认的对象
Button btnDef = (Button)LoadXaml("btns/btn4.xaml");
sp.Children.Add(btnDef);
}
/// <summary>
/// 从xaml文件中 创建 xaml对象
/// </summary>
/// <param name="file">xaml文件的"地址"</param>
/// <returns>返回xaml文件定义的对象</returns>
public static object LoadXaml(string file)
{
Uri fileUri = new Uri(file, UriKind.Relative);
System.Windows.Resources.StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(fileUri);
if ((streamInfo != null) && (streamInfo.Stream != null))
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(streamInfo.Stream))
{
return System.Windows.Markup.XamlReader.Load(reader.ReadToEnd());
}
}
//若文件不存在,则返回默认创建的对象
return CreateDefaultObject();
}
//创建默认对象,以一个简单的button为例
public static object CreateDefaultObject()
{
Button btn = new Button();
btn.Width = 60;
btn.Height = 50;
btn.Foreground = new SolidColorBrush(Colors.Blue);
btn.Content = "Default";
return btn;
}
}