wpfxamlxml-namespaces

WPF - globally add xaml namespace declaration


I have quite a huge WPF application with a lot of XAML files. Every single XAML file has from 5 to 10 clr to xml namespace mappings xmlns:abc="clr-namespace:Abcdef".
It looks awful and is a pain to write in each and every file.

Is there a way to define those globally?


Solution

  • There is no way to define them globally across files. This is a limitation of XML; XAML is a subset of it.

    However you can clean them up a bit using XmlnsDefinition

    See this article: http://zachbonham.blogspot.com/2010/04/organize-xaml-namespace-declarations.html

    If you started with this XAML:

    <UserControl
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:treeView="clr-namespace:MaryKay.SamPortal.Common.UI.TreeView.Views;assembly=MaryKay.SamPortal.Common.UI"
        xmlns:infoBar="clr-namespace:MaryKay.SamPortal.Common.UI.InfoBar.Views;assembly=MaryKay.SamPortal.Common.UI">
      <infoBar:InformationBar DataContext="{Binding InfoBar}"/>
    </UserControl>
    

    And added these XmlnsDefinition attributes:

    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.InfoBar.Views")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.RoleGroupPicker.Views")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.BetterPopup")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.TextEditor")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.Converters")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.Documents")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.SplashScreen")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.TemplateSelector")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.ModalDialog")]
    [assembly: XmlnsDefinition("urn:marykay-samportal-common-ui", "MaryKay.SamPortal.Common.UI.ConsultantSearch.Views")]
    // etc...
    

    You could end up with this XAML instead:

    <UserControl
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:commonUI="urn:marykay-samportal-common-ui">
      <commonUI:InformationBar DataContext="{Binding InfoBar}"/>
    </UserControl>