WPF中的命名空间XAML

WPF中的命名空间XAML

开发工具与关键技术:Visual Studio 2015、WPF
作者:黄元进
撰写时间:2019年5月5日

我们通常能看到xaml文件开头有一个类似http协议的字串,因为是自动生成,也没太在乎。但是在迁移引用第三方控件的项目时,往往会因此而引发一些错误,我们来看看这些http字串到底表示着什么?

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="MainWindow" Height="1080" Width="1920">
<Grid>
</Grid>
</Window>

虽然会用到clr-namespace,这是引用命名空间(程序集),但是对于网址开头的命名空间有可能就有点疑惑了,它究竟代表的是个网址?xaml文件被解析的时候会访问这个网址吗?如果这个网址哪天不能get了,那我们的程序是不是就不能正常运行了。
在这里我先把结论告诉大家,然后在一步步分析是为什么。
其实,很简单,以xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation这个字串为例,其实就是System.Windows,System.Windows.Automation,System.Winjdows.Controls…等一系列命名空间的集合,是这个集合的【别名】,在浏览器输入这个网址有时候是不可访问的。如果自己定义类库的话,我把这个【别名】叫做张三也是可以的。微软建议,这个一般定义为公司网址,或者个人网址。

  1. 反编译
    每个"网址"其实都代表着后台常见的一个命名空间,做了一个映射,所以我们引用不同系统自带dll组件,会自动添加不同的"网址"。
    2.自定义一个"网址"命名空间
    新建一个类库(此处命名为ClassLibrary1),然后添加一个自定义控件,在程序集信息AssemblyInfo.cs文件中添加下面这句话:
//用网址映射常规命名空间
ClassLibrary1[assembly: XmlnsDefinition("http://agriplatform.top", "ClassLibrary1")]

XmlnsDefinition需要用到System.Windows.Markup命名空间,请务必引用System.Xaml.dll,WindowsBase.dll两个程序集,否则没有该函数。
指定 XAML 命名空间与 CLR 命名空间之间按程序集进行的映射,然后 XAML 对象编写器或 XAML 架构上下文将其用于类型解析。可能一些基础不好的需要写全,这边我把自定义的控件贴出来。

<UserControl x:Class="ClassLibrary1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="20" d:DesignWidth="30" x:Name="MyControl">
    <Grid>
        <Button x:Name="UserBtn" Width="30" Height="20" Content="你好"/>
    </Grid>
</UserControl>

3.解析"网址"命名空间
新建一个WPF工程,我们这里给出两种引用方式,包括网址。

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ss="http://agriplatform.top"
        xmlns:local="clr-namespace:ClassLibrary1;assembly=ClassLibrary1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ss:UserControl1/> 
    </Grid>
</Window>

是不是看到有个ss引用网址,非常简单。
总结:xaml网址是一个对应普通命名空间的映射,也可以不用网址形式

猜你喜欢

转载自blog.csdn.net/weixin_44547949/article/details/89855944
今日推荐