我有一个非常简单的用户控件,我正在尝试在 XAML 中实例化它。我发现当我对命名空间有点过分热情时,我会遇到 x:Name 的问题。
这是我的用户控件:
<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>
这是 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:Name 应用于 UserControl,构建将失败,如下所示:
<control:UserControl1 x:Name="test"/>
这将使构建失败,并出现以下错误:
Type 'UserControlTest.UserControlTest.UserControl1' is not defined.
任何人都可以解释为什么?我是否需要避免将我的 UserControls 放入命名空间,以便为它们提供 x:Name 值?我想从代码隐藏操作我的 UserControls,如果没有 x:Name,我就在小溪上。但我不想为了获得它而牺牲命名空间的使用!
非常感谢。
最佳答案
我遇到了同样的问题(重建项目后,首先它工作正常......)。我把UserControl
进入单独的命名空间。
关于wpf - UserControl 中过度指定的命名空间失败 WPF 构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1104978/