XAML命名空间命名约定

3

我有一个C# WPF项目,命名空间为test。在XAML中,我应该如何命名子命名空间?

<Window x:Class="test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      
    xmlns:local="clr-namespace:test"
    xmlns:local.c="clr-namespace:test.Converters"   
    xmlns:local.v="clr-namespace:test.Validators"       
    Title="MainWindow" Height="360" Width="640"> ....

我这里有一个惯例,就是用句点来分隔子包。这样做可以吗?

祝好,

e.


无论你和你的团队想要什么,这只是一个本地别名。 - Diego Mijelshon
我是C#的新手,所以我想问 - 人们通常选择什么? :-o - emesx
就我个人而言,我不会创建层次结构:你可以在那里放置 testConvertersValidators。但是再次强调,除了“任何有效的方法”之外,没有其他约定。 - Diego Mijelshon
我有 Java 的背景,在 Java 中,惯例就像教条一样。;-) - emesx
2个回答

10
如果可能的话,更好的做法是将您使用的C#命名空间与WPF命名空间分开。这也将减少您所拥有的导入数量。这可以通过XmlnsDefinition类来完成。
<Window x:Class="test.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      
  xmlns:test="http://whatever.com/test">
在你的库的AssemblyInfo.cs中,你只需要添加以下内容:
[assembly: XmlnsDefinition("http://whatever.com/test", "test")]
[assembly: XmlnsDefinition("http://whatever.com/test", "test.Converters")]
[assembly: XmlnsDefinition("http://whatever.com/test", "test.Validators")]
[assembly: XmlnsDefinition("http://whatever.com/test", "test.CustomControls")]
请注意,只有在引用类的程序集与您所引用它们的程序集不同时,此方法才有效。在同一程序集中,仍需要使用C#命名空间。
您甚至可以通过将命名空间添加到WPF XML命名空间来完全消除导入:
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "test")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "test.Converters")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "test.Validators")]

这使得人们可以编写:

<Window x:Class="test.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      
  >
  <!-- Note: no namespace prefix needed! -->
  <YourCustomControl />

谢谢,我所有的类都在同一个程序集中。 - emesx

2

典型的WPF应用程序在XAML中并没有一个命名空间约定,除了默认的xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"、Blend设计时命名空间和xmlns:local,通常会引用当前命名空间。

在您上面描述的场景中,我见过/使用了一些变体,例如:

<Window x:Class="test.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      
  xmlns:local="clr-namespace:test"
  xmlns:c="clr-namespace:test.Converters"   
  xmlns:v="clr-namespace:test.Validators">

或者

<Window x:Class="test.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      
  xmlns:local="clr-namespace:test"
  xmlns:conv="clr-namespace:test.Converters"   
  xmlns:val="clr-namespace:test.Validators">

最终,真正的决定权在于你和你的团队达成的共识。

1
谢谢您提供简明扼要的答案 :) - emesx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接