C# 从XAML将基元类型作为参数传递
TL;DR-我在Silverlight中将系统类型作为值传递给类型参数时遇到问题。这是某种已知的问题吗?有可能吗 详细信息:C# 从XAML将基元类型作为参数传递,c#,.net,silverlight,xaml,C#,.net,Silverlight,Xaml,TL;DR-我在Silverlight中将系统类型作为值传递给类型参数时遇到问题。这是某种已知的问题吗?有可能吗 详细信息: 在我的控件中,我具有类型为type的依赖属性。从系统命名空间传递类型时存在问题,例如int(Int32),string(string),Guid,decimal(decimal),bool(Boolean)。在这些情况下,Dependence属性接收null值(Dependence属性默认值设置为一些非null值,因此我在OnPropertyChanged事件中看到传递了
在我的控件中,我具有类型为
type
的依赖属性。从系统
命名空间传递类型时存在问题,例如int(Int32)
,string(string)
,Guid
,decimal(decimal)
,bool(Boolean)
。在这些情况下,Dependence属性接收null
值(Dependence属性默认值设置为一些非null值,因此我在OnPropertyChanged事件中看到传递了null
)。对于其他类型,它可以正常工作
以下是“我的依赖项”属性的代码:
public static readonly DependencyProperty SomeTypeProperty = DependencyProperty.Register(
"SomeType", typeof(Type), typeof(Control1), new PropertyMetadata(typeof(EmptyType), OnSomeTypePropertyChanged));
public Type SomeType
{
get { return (Type)GetValue(SomeTypeProperty); }
set { SetValue(SomeTypeProperty, value); }
}
<local:SilverlightControl1 MyType="{Binding Source={StaticResource booleanRes},Path=TypeOf}"/>
以及控件的用法:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
[...]
<sl1:Control1 SomeType="sys:Boolean" />
xmlns:sys=“clr命名空间:系统;程序集=mscorlib”
[...]
有趣的是-它在VisualStudio的XAML designer中工作。我通过在我的
Control1
控件的内容中显示属性值以及传递的类型来了解这一点。但在Silverlight运行时环境中,它不起作用。我不知道为什么会发生这种情况。。。然而,这里有一个解决办法
public class TypeOfRes
{
public object Object { get; set; }
public Type TypeOf
{
get { return Object == null ? null : Object.GetType(); }
}
}
<local:TypeOfRes x:Key="booleanRes">
<local:TypeOfRes.Object>
<sys:Boolean>True</sys:Boolean>
</local:TypeOfRes.Object>
</local:TypeOfRes>
符合事实的
public static readonly DependencyProperty SomeTypeProperty = DependencyProperty.Register(
"SomeType", typeof(Type), typeof(Control1), new PropertyMetadata(typeof(EmptyType), OnSomeTypePropertyChanged));
public Type SomeType
{
get { return (Type)GetValue(SomeTypeProperty); }
set { SetValue(SomeTypeProperty, value); }
}
<local:SilverlightControl1 MyType="{Binding Source={StaticResource booleanRes},Path=TypeOf}"/>
我知道有一些解决方法,包括为我想使用的每种类型声明资源,但是我只是好奇为什么会发生这种情况?有没有可能用一种好的、干净的方式来做呢?这样就不需要从名称中解析类型,也不需要单独处理每个有问题的类型等等。