XmlnsDefinitionAttribute Is Pretty Nifty

本文介绍如何在XAML中声明自定义控件的XML命名空间,使用CLR命名空间进行映射。通过使用System.Windows.Markup命名空间中的XmlnsDefinitionAttribute属性简化语法,提高代码可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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:)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值