【发布时间】:2012-09-03 11:12:38
【问题描述】:
为什么当我为我的 MVVM 视图创建一些设计时数据时,我必须嵌套两次 xmlns 才能访问属性的属性?
例子:
<d:DesignProperties.DataContext>
<local:UserListViewModel>
<local:UserListViewModel.Users xmlns:local="clr-namespace:ChatModule.ViewModels">
<local:User Name="Person 1" />
<local:User Name="Person 2" />
<local:User Name="Person 3" />
<local:User Name="Person 4" />
<local:User Name="Person 5" />
<local:User Name="Person 6" />
</local:UserListViewModel.Users>
</local:UserListViewModel>
</d:DesignProperties.DataContext>
我已经在 UserControl 的 xmlns 中定义了一个本地属性。但是要访问底层类中的 User 结构,我必须在 Users 属性中再次定义它。
这是为什么呢?
这一切都很好......我可以看到我的运行时数据,这很棒。我以前从来没有这样做过,所以能够看到它很整洁。我注意到我经常遇到错误,这些错误在我编译时会消失……但每当我更改 xaml 时就会再次出现。
The property 'Name' was not found in type 'User'.
The property 'Name' was not found in type 'User'.
The property 'Name' was not found in type 'User'.
The property 'Name' was not found in type 'User'.
The property 'Name' was not found in type 'User'.
The property 'Name' was not found in type 'User'.
显然它可以工作,否则我将无法看到运行时数据。
我还想将此设计时数据提取到另一个 xaml 类中,并在此类中引用它,因此我没有位于视图本身内的实际设计时数据......只是对另一个 xaml 文件的引用。
所以我已经这样做了......就像这样......
<UserListViewModel xmlns="clr-namespace:ChatModule.ViewModels">
<UserListViewModel.Users xmlns:local="clr-namespace:ChatModule.ViewModels">
<local:User Name="Person 1" />
<local:User Name="Person 2" />
<local:User Name="Person 3" />
<local:User Name="Person 4" />
<local:User Name="Person 5" />
<local:User Name="Person 6" />
</UserListViewModel.Users>
</UserListViewModel>
但是,当我摆脱代码隐藏时,我得到了上面提到的相同错误(在构建中消失),但还有一个错误提示
Cannot set properties on propety elements. Line 2 Position 6.
与其他错误不同,这不允许我构建。为什么是这样?我如何解决它?我还在习惯这种设计时数据的东西。
【问题讨论】:
-
嗯...当我像在第二部分中那样将它托管在一个新的 xaml 文件中时,我不能拥有第二个 xmlns:local。这就是导致问题的原因。为什么在实际视图 xaml 中需要它,而不是在这个单独的 xaml 文件中?为什么会这样?
-
仅供参考,最好将您的发现作为答案发布,而不是更新问题。感谢您的帖子。
-
谢谢。我希望我仍然可以得到答案,为什么在“用户”类型中找不到属性“名称”错误仍然出现......但大部分问题至少得到了回答。我继续前进并将我的编辑作为答案。我对stackoverflow还是很陌生,所以请原谅我。
标签: wpf mvvm blendability