WFP加载xml文档生成wpf界面UI

来源:互联网 发布:阿里云服务器退款 编辑:程序博客网 时间:2024/04/28 01:44

转自:http://zjysky.blog.hexun.com/48948550_d.html

 

WPF的界面元素都是xaml标签,当然也是xml标签,可以将ui文档放到一个xml文件中,然后动态的去读取xml文件中xaml标签,然后现在到wpf的window中

 

方法

1。先创建一个xml文件,里面放xaml的标签元素

需要注意的是是Grid元素的xmln标签一定不能少,而且要将xml文件作“资源”进行设置

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Border Margin="40,59,60,141" Name="border1" Background="Cyan" BorderBrush="Beige" >
        <Button Name="b1" Content="test" Width="80" Height="50" ></Button>
    </Border>
</Grid>

2。在wpf的方法中添加这样的读取代码

using System.Windows.Markup;

 

 Uri uri = new Uri("pack://application:,,,/test.xml");//加载资源,注意格式,最后有个/
            Stream s = App.GetResourceStream(uri).Stream;//读取资源流
            FrameworkElement fe = XamlReader.Load(s) as FrameworkElement;
            Content = fe;//将从xml读取的元素赋值给窗体的Content

这样就可以显示了你在xml中设置的ui元素了

资源添加到wpf的window中以后,就可以使用findname方法来找到某些元素,然后进行其他附加操作

 

特2:

也可以使用window标签作为xml文件的元素标签,这意味着我们就是要生成一个window对象。

<window  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">

<Grid>
    <Border Margin="40,59,60,141" Name="border1" Background="Cyan" BorderBrush="Beige" >
        <Button Name="b1" Content="test" Width="80" Height="50" ></Button>
    </Border>
</Grid>

</window>

在app的代码这样写,在启动方法中

 Uri uri = new Uri("pack://application:,,,/test.xml");
            Stream s = App.GetResourceStream(uri).Stream;
            window w = XamlReader.Load(s) as window;

window.addHander();//添加某些按钮或者其他控件的事件发方法

app.run(w);

这样就可以从xml文档中装载一个window元素对象

 

原创粉丝点击