问题
I've got a view that shows only a Label.
The viewmodel is injected correctly in the view because the text of the label is bound to a viewmodel property. Now, if I try to define a DataGrid in the xaml, I've got a XamlParseException:
{System.Windows.Markup.XamlParseException: Type 'DataGrid' not found. [Line: 16 Position: 45] su System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) su Common.Views.FunctionalityView.InitializeComponent() su Common.Views.FunctionalityView..ctor(IFunctionalityViewModel viewModel)}
BUT if I define a DataGrid myDg = new DataGrid()
right before the InitializeComponent();
it works.
I've checked all references and still can't find the problem.
回答1:
It sounds like your default namespace is messed up or missing. Without the xaml, it is hard to tell what you should do.
An easy way to figure this out for yourself is to create a new UserControl, then examine and compare the xmlns namespaces defined on its root with the root element of your View.
WPF locates types by a specialized namespace definition. It follows the format
clr-namespace:[namespace](;assembly=[assembly name])
where
[namespace]
is the namespace that contains the type definition. And, if the type is defined within a different assembly from the one where the xaml file is located, you have to include the part within the preface. [assembly name]
is the name of the assembly without the .dll extension (e.g., assembly=mscorlib
would import mscorlib.dll
). To import the Int32 type and use it within your xaml, you'll have to define the namespace
xmlns:s="clr-namespace:System;assembly=mscorlib"
There also exists an assembly-level attribute which allows you to assign a different namespace for all types within an assembly. Typically, this takes the form of a URL. This is by tradition rather than necessity, IIRC. This is why some controls are identified with a more traditional namespace, such as
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
来源:https://stackoverflow.com/questions/8852912/xamlparseexception-in-view