XmlnsDefinitionAttribute Is Pretty Nifty

 When we want to declaratively use our custom controls or reference the types we defined in XAML, we should declare the XML namespace to map to the CLR namespace in which the controls and types are defined as the following XAML snippt demonstrates:

<Page x:Class="Test.MainWindow"          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:cc="clr-namespace:Sheva.Windows.Controls;assembly=AvalonLib"/>

    Recently, I am heavily engaged with writing a resuable WPF control library, and quite often I need to create some pages to test those controls I create, so ever now and then I have to use the cumbersome syntax like above to declare the XML namespace, personally I don't like the syntax, and I thought Microsoft WPF team should come up with a more elegant way of doing it, and in actuality, they did introduce an alternative to do it since the CTP releases. there is a custom attribute called XmlnsDefinitionAttribute in the System.Windows.Markup namespace which allows you to apply to the assembly which contains the types and controls the XAML code would reference.the built-in WPF assemblies such as WindowsBase.dll, PresentationCore.dll, and PresentationFramework.dll all have this attribute applied, and all have http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace mapped with the CLR namespaces introduced by them. and of cause you can use this attribute in your own project, just open the AssemblyInfo.cs file, and append the following directive:

[assembly: XmlnsDefinition("http://schemas.sheva.com/wpf/""Sheva.Windows.Controls")]

    Then you can declare the namespace alias in XAML this way:

<Page x:Class="Test.MainWindow"          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:cc="http://schemas.sheva.com/wpf/"/>

        Wow, this is a bit like the built-in xmlns declaration indeed, really really cool indeed:)

posted @   遥望星空  阅读(435)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示