星空雅梦

WPF入门教程(十六)命名空间XAML

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

  1.  
    <Window x:Class="WpfApplication1.MainWindow"
  2.  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.  
    Title="MainWindow" Height="1080" Width="1920">
  5.  
    <Grid>
  6.  
    </Grid>
  7.  
    </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文件中添加下面这句话:

  1.  
    //用网址映射常规命名空间ClassLibrary1
  2.  
    [assembly: XmlnsDefinition("http://agriplatform.top", "ClassLibrary1")]

XmlnsDefinition需要用到System.Windows.Markup命名空间,请务必引用System.Xaml.dll,WindowsBase.dll两个程序集,否则没有该函数。

指定 XAML 命名空间与 CLR 命名空间之间按程序集进行的映射,然后 XAML 对象编写器或 XAML 架构上下文将其用于类型解析。可能一些基础不好的需要写全,这边我把自定义的控件贴出来。

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

3.解析"网址"命名空间

新建一个WPF工程,我们这里给出两种引用方式,包括网址。

  1.  
    <Window x:Class="WpfApplication1.MainWindow"
  2.  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.  
    xmlns:ss="http://agriplatform.top"
  5.  
    xmlns:local="clr-namespace:ClassLibrary1;assembly=ClassLibrary1"
  6.  
    Title="MainWindow" Height="350" Width="525">
  7.  
    <Grid>
  8.  
    <ss:UserControl1/>
  9.  
    </Grid>
  10.  
    </Window>

是不是看到有个ss引用网址,非常简单。

总结

xaml网址是一个对应普通命名空间的映射,也可以不用网址形式。

原文地址:https://www.cnblogs.com/LiZhongZhongY/p/10871755.html