尝试在Visual Studio 2010中调试Silverlight 4应用程序时出现此异常。在通过InitializeComponent()
行后将抛出异常。该异常仅在调试期间发生,但它似乎不是Visual Studio Designer的问题。
System.Windows.Markup.XamlParseException occurred
Message=Failed to create a 'System.Type' from the text 'local:CustomerEntity'. [Line: 11 Position: 59]
LineNumber=11
LinePosition=59
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at TestSilverlightApp.MainPage.InitializeComponent()
at TestSilverlightApp.MainPage..ctor()
InnerException:
所以我正在尝试做的事情:我创建了这个ViewModel
类,它具有类型为EntityType
的{{1}}属性,其值将在XAML中赋值。< / p>
我创建了一个新的最小项目,它将重现同样的问题,见下文。
这是Silverlight应用程序的System.Type
。已分配RootVisual
的{{1}}在ViewModel
。
我还将EntityType
绑定到UserControl.Resources
,并故意在正文中创建一个绑定到ViewModel
参数的DataContext
元素。 Visual Studio Designer显示已分配的Run
的类型名称没有问题。
如果我没有在XAML中设置EntityType
参数,则不会发生错误。
EntityType
此异常将在通过下面的EntityType
行后抛出。
<UserControl x:Class="TestSilverlightApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestSilverlightApp"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<local:ViewModel x:Key="rootViewModel" EntityType="local:CustomerEntity" />
</UserControl.Resources>
<StackPanel x:Name="LayoutRoot" DataContext="{StaticResource rootViewModel}">
<TextBlock><Run Text="{Binding EntityType}" /></TextBlock>
</StackPanel>
</UserControl>
ViewModel类具有EntityType属性,该属性接受InitializeComponent()
值。
namespace TestSilverlightApp
{
public partial class MainPage : System.Windows.Controls.UserControl
{
public MainPage()
{
InitializeComponent();
}
}
}
这只是我为了将其Type分配给ViewModel.EntityType属性而创建的空类。
System.Type
关于如何解决这个问题的任何想法?我宁愿不实现自己的namespace TestSilverlightApp
{
public class ViewModel
{
public System.Type EntityType { get; set; }
}
}
或其他东西来在XAML中设置namespace TestSilverlightApp
{
public class CustomerEntity
{ }
}
值。
答案 0 :(得分:0)
您可以使用以下类型转换器: -
public class TypeTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(System.Type);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
return Type.GetType((string)value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
return value.ToString();
}
}
在您查看模型代码时使用: -
public class ViewModel
{
[TypeConverter(typeof(TypeTypeConverter))]
public System.Type EntityType { get; set; }
}
您不能使用命名空间别名来定义类型,它必须是静态GetType
方法识别的类型: -
<local:ViewModel x:Key="rootViewModel" EntityType="TestSilverlightApp.CustomerEntity" />