2009-07-09 178 views
0

我有一個非常簡單的用戶控件,我試圖在XAML中實例化它。我發現,當我對命名空間有些過分熱情時,我遇到了x:Name的問題。用戶控件中的Overspecified命名空間失敗WPF構建

這裏是我的用戶:

<UserControl x:Class="UserControlTest.UserControl1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="300"> 
<Grid> 
    <Label Name="Label1">Label</Label> 
</Grid> 
</UserControl> 

這裏是代碼隱藏的用戶控件:

Namespace UserControlTest 
Partial Public Class UserControl1 

End Class 
End Namespace 

現在,請注意,我有我的VB.Net項目設置的根命名空間「UserControlTest」。知道了,看看我的主窗口: 這裏是我的主窗口:

<Window x:Class="Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:control="clr-namespace:UserControlTest.UserControlTest" 
Title="Window1" Height="300" Width="300"> 
<Grid> 
    <control:UserControl1 /> 
</Grid> 
</Window> 

見控制別名如何需要有「UserControlTest.UserControlTest」?這是因爲我的項目的根名稱空間設置爲UserControlTest,並且我還將UserControl的名稱空間定義爲UserControlTest。如果我不使用UserControl的命名空間,我沒有任何麻煩。

但是,因爲我已經做到了這一點,構建失敗,我應該試着申請一個X:名字到用戶控件,如下所示:

<control:UserControl1 x:Name="test"/> 

這將構建失敗,這個錯誤:

Type 'UserControlTest.UserControlTest.UserControl1' is not defined. 

有人可以解釋爲什麼嗎?我是否需要避免將UserControls放入命名空間中,以便我可以給它們使用x:Name values?我想操作我的UserControls從代碼隱藏,並沒有一個x:Name,我上了小溪。但我不想犧牲命名空間的使用來獲得它!

非常感謝。

回答

0

在用戶控件的代碼隱藏中定義的名稱空間是什麼?

如果您的項目名爲Foo,並且該項目中有一個名爲Controls的文件夾,則添加到該文件夾​​的任何新用戶控件都將被賦予命名空間Foo.Controls。

然後在你的XAML可以參考它像這樣:

xmlns:Controls="clr-namespace:Foo.Controls" 
... 
<Controls:UserControl1 x:Name="uc1"/> 

好像你有一個命名問題。

編輯:

這裏是我如何做它在我的一個項目。

StatusBar.xaml.cs

namespace Client.Controls.UserControls 
{ 
public partial class StatusBar : UserControl 
{ 
... 
} 
} 

StatusBar.xaml

<UserControl x:Class="Client.Controls.UserControls.StatusBar"> 
</UserControl> 

Main.xaml.cs

using Client.Controls.UserControls; 

namespace Client 
{ 
public partial class Main : Window 
{ 
... 
} 
} 

主。xaml

<Window x:Class="Client.Main" 
xmlns:UserControls="clr-namespace:Client.Controls.UserControls"> 
<UserControls:StatusBar x:Name="mainStatusBar" /> 
</Window> 
+0

我的用戶控件沒有在代碼隱藏中定義的名稱空間。 你確定有關Foo.Controls的命名嗎?我添加了一個Controls文件夾和一個新的UserControl。它沒有在代碼隱藏中定義的名稱空間。我的主窗口XAML有xmlns:control =「clr-namespace:UserControlTest」(即NOT clr-namespace:UserControlTest.Control),並且能夠使用control:前綴在XAML中創建新的UserControl。 – TimH 2009-07-09 18:07:55

2

我有同樣的問題(重建項目後,首先它工作正常...)。我把UserControl分成不同的名字空間。

0

我在vb.net項目中遇到了同樣的問題,儘管嘗試了這裏和其他地方的建議,但無法解決問題。事實上,我能夠將我們項目中完全相同的代碼帶入新項目,並且它工作得很好(據我所知,新項目中的所有配置都是相同的)。在David提供的解決方案中,我注意到他正在使用c# - 我想知道這是否與vb.net相關的一些古怪。

最後,我需要使用的用戶控件非常簡單,我實現了它作爲資源ControlTemplate來解決問題。對不起,我沒有更好的答案,我真的不滿意我的發現......