WPF 自定义控件库名称空间
写WPF项目时,是否有见过有的第三方ui控件库,引用时在xaml文件中使用的是类似网址样式的名称空间?

如上,使用handycontrol库时,我们会引入:xmlns:hc="https://handyorg.github.io/handycontrol",然后就可以使用hc来使用handycontrol库中的各种控件了。
咦?是不是觉得好方便哇!!!
handycontrol是怎么做到的?
让源码来说话,我们跑到handycontrol的控件库git仓库中一探究竟:

原来是在项目属性文件中加入 XmlnsDefinition 和 XmlnsPrefix 就可以diy自己的控件库名称空间别名了。
为什么会有这种形式的空间名称?
因为方便;如果没有这种操作,控件库的控件类型可能在不同的名称空间中,使用的时候难道要写 xmlns:hc1、xmlns:hc2、...写一堆么?有了这个映射技巧,就可以只引入一个网址形式的字符串去引用控件库下的各种控件了。
连前缀都可以不带?
不知道你是否有注意过,直接可以在xaml文件中敲出其类型而不需要加入空间前缀。如<Button/>,你不会去写<xxxx:Button/>对吧?这是为什么?
继续让源码来说话,我们跑到wpf提供的内置控件库wpf控件库看一下:

可以看到wpf把Button、Window等等这些控件所在的名称空间映射到了 http://schemas.microsoft.com/winfx/2006/xaml/presentation、http://schemas.microsoft.com/winfx/2007/xaml/presentation、http://schemas.microsoft.com/winfx/2009/xaml/presentation
下面了。
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
</UserControl>
而我们新建一个窗体或者用户控件,IDE帮我们默认生成的文件必然会带着xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation";这就解释了Button、Window为什么不用带前缀了:因为都被映射到了默认空间中了。
由此,我们也可以比葫芦画瓢,修改我们的控件库项目中的AssemblyInfo文件:
//在你的项目的AssemblyInfo.cs文件中添加 注意按需添加 通常只需把控件所在的空间映射过去
[assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "bigboss.ui")]
[assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "bigboss.controls")]
[assembly:System.Windows.Markup.XmlnsPrefix ("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "bigboss")]
如此便把我们的项目也映射到和Button一样的默认名称空间里面了;那么之后在别的项目的xaml文件中,使用你这个程序集的控件,就不需要写"烦人"的前缀了。

浙公网安备 33010602011771号