【问题标题】:Pass primitive Type as a parameter from XAML将原始类型作为 XAML 中的参数传递
【发布时间】:2014-05-27 10:59:08
【问题描述】:

TL;DR - 我在将系统类型作为值传递给 Silverlight 中的类型参数时遇到问题。这是某种已知问题吗?有可能吗?

详细说明:
在我的控制中,我有 Type 类型的依赖属性。从System 命名空间传递类型存在问题,例如int(Int32)string(String)Guiddecimal(Decimal)bool(Boolean)。在这些情况下,依赖属性接收 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); }
}

以及控件的用法:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
[...]
<sl1:Control1 SomeType="sys:Boolean" />

有趣的是 - 它在 Visual Studio 的 XAML 设计器中工作。 我通过在我的 Control1 控件的内容中显示属性值以及传递的类型来知道这一点。但是在 Silverlight 运行时环境中它不起作用。

【问题讨论】:

    标签: c# .net silverlight xaml


    【解决方案1】:

    我不知道为什么会这样...但是,这里有一个解决方法..

    1. 创建以下类:

      public class TypeOfRes
      {
          public object Object { get; set; }
      
          public Type TypeOf
          {
              get { return Object == null ? null : Object.GetType(); }
          }
      }
      
    2. 在您的页面中创建以下资源:

      <local:TypeOfRes x:Key="booleanRes">
          <local:TypeOfRes.Object>
              <sys:Boolean>True</sys:Boolean>
          </local:TypeOfRes.Object>
      </local:TypeOfRes>
      
    3. 引用您的资源中的资源:

      <local:SilverlightControl1 MyType="{Binding Source={StaticResource booleanRes},Path=TypeOf}"/>
      

    【讨论】:

    • 我知道有一些解决方法,包括为我想使用的每种类型声明资源,但是我只是好奇为什么会这样?是否有可能以漂亮、干净的方式进行 - 因此无需从名称中解析类型,单独处理每个有问题的类型等。
    猜你喜欢
    • 2011-01-14
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2015-02-22
    • 1970-01-01
    • 2019-02-27
    • 2016-08-07
    相关资源
    最近更新 更多