我有一个包含 2 个项目的 WPF 应用程序,一个用于 ViewModels (MyApp.Core),另一个用于 Views (MyApp)。
在 View 和 ViewModel 内部,我有不同的嵌套命名空间(例如:MyApp.Core.ViewModels.Example1)。
我想在 App.xaml 中注册我的 View 和 ViewModel,并使用 DataTemplates 将 ViewModel 绑定(bind)到 View 。
我目前拥有的是:
<Application
x:Class="MyApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:example1v="clr-namespace:MyApp.Views.Example1"
xmlns:example1vm="clr-namespace:MyApp.Core.ViewModels.Example1;assembly=MyApp.Core"
xmlns:example2v="clr-namespace:MyApp.Views.Example1"
xmlns:example2vm="clr-namespace:MyApp.Core.ViewModels.Example1;assembly=MyApp.Core"
StartupUri="Views/MainWindow.xaml">
<Application.Resources>
<DataTemplate DataType="{x:Type example1vm:Example1ViewModel}">
<example1v:Example1Window />
</DataTemplate>
<DataTemplate DataType="{x:Type example2vm:Example2ViewModel}">
<example2v:Example2Window />
</DataTemplate>
</Application.Resources>
</Application>
如您所见,我为每个嵌套命名空间都有一个命名空间,并且随着应用程序的增长,该命名空间会变得更大。
我的问题是:有没有办法只导入基本命名空间,然后在 XAMl 标记中指定更多内容?
我正在考虑这样的事情:
<Application
x:Class="MyApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:v="clr-namespace:MyApp.Views"
xmlns:vm="clr-namespace:MyApp.Core.ViewModels;assembly=MyApp.Core"
StartupUri="Views/MainWindow.xaml">
<Application.Resources>
<DataTemplate DataType="{x:Type vm:Example1.Example1ViewModel}">
<v:Example1.Example1Window />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:Example2.Example2ViewModel}">
<v:Example2.Example2Window />
</DataTemplate>
</Application.Resources>
</Application>
最佳答案
<object property="{x:Type prefix:typeNameValue}" .../>
prefix
Optional. A prefix that maps a non-default XAML namespace. Specifying a prefix is frequently not necessary. See Remarks.
typeNameValue
Required. A type name resolvable to the current default XAML namespace; or the specified mapped prefix if prefix is supplied.
快速测试显示 typeNameValue
中的化合物名称实际上只是有效 - 因为它显然可以解析为命名空间前缀 - 尽管 XAML 设计器可能会提示不支持嵌套类型。
namespace DataTypeNamespaceTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Test.ViewModel();
}
}
}
namespace DataTypeNamespaceTest.Test
{
public class ViewModel
{
public string Text { get; } = "Text in Test.ViewModel";
}
}
XAML:
<Window x:Class="DataTypeNamespaceTest.MainWindow"
xmlns:local="clr-namespace:DataTypeNamespaceTest"
...>
<Window.Resources>
<DataTemplate DataType="{x:Type local:Test.ViewModel}">
<TextBlock Padding="10" Background="Aqua" Text="{Binding Text}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding}"/>
</Grid>
</Window>
关于c# - 如何从 XAML 内部访问嵌套命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58857034/