当前位置: 移动技术网 > IT编程>开发语言>c# > 在WPF中动态加载XAML中的控件实例代码

在WPF中动态加载XAML中的控件实例代码

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文实例讲述了在wpf中动态加载xaml中的控件的方法。分享给大家供大家参考,具体如下: using system; using system.collecti

本文实例讲述了在wpf中动态加载xaml中的控件的方法。分享给大家供大家参考,具体如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.windows;
using system.windows.controls;
using system.windows.data;
using system.windows.documents;
using system.windows.input;
using system.windows.media;
using system.windows.media.imaging;
using system.windows.navigation;
using system.windows.shapes;
using system.io;
using system.xml;
using system.windows.markup;
/*
 * 功能:测试wpf中动态加载xaml中的控件
 *    并加到指定的子节点中。
 * 作者:kagula
 * 时间:2012-09-20
 * 环境:vs2008 .net framework 3.5
 * 参考资料:[1]《application=code+markup 读书笔记 19》
 *        http://space.itpub.net/15123181/viewspace-423015
 *      [2]《pack uris in windows presentation foundation》
 *        http://technet.microsoft.com/en-us/library/aa970069(v=vs.90)
 */
namespace testxamlload
{
  /// <summary>
  /// interaction logic for window1.xaml
  /// </summary>
  public partial class window1 : window
  {
    public window1()
    {
      initializecomponent();
      //loadembeddedxaml();
      //loadembeddedxaml2();
      loadembeddedxaml3();
    }
    //从字符串中加载
    public void loadembeddedxaml()
    {
      title = "load embedded xaml";
      string strxaml = "<button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'" +
        " foreground='lightseagreen' fontsize='16pt' width='128' height='32'>" +
        " from string object!</button>";
      stringreader strreader = new stringreader(strxaml);
      xmltextreader xmlreader = new xmltextreader(strreader);
      object obj = xamlreader.load(xmlreader);
      grid1.children.add((uielement)obj);
    }
    //从外部文件中加载 button控件
    public void loadembeddedxaml2()
    {
      xmltextreader xmlreader = new xmltextreader("d:\\a.xaml");
      uielement obj = xamlreader.load(xmlreader) as uielement;
      grid1.children.add((uielement)obj);
    }
    //从资源文件中加载
    public void loadembeddedxaml3()
    {
      //build action = resource,do not copy,无相应cs文件
      uri uri = new uri("/loadxamlresource.xaml",urikind.relative);
      stream stream =application.getresourcestream(uri).stream;
      //frameworkelement继承自uielement
      frameworkelement obj =xamlreader.load(stream) as frameworkelement;
      grid1.children.add(obj);
    }
  }
}

xaml文件中的清单

<button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
  foreground='lightseagreen'
  fontsize='16pt'
  width='128'
  height='32'>
  from file object!
</button>

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#程序设计之线程使用技巧总结》、《c#操作excel技巧总结》、《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网