65.9K
CodeProject 正在变化。 阅读更多。
Home

在 XAML 中传递日期

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2009年10月20日

CPOL

2分钟阅读

viewsIcon

31706

downloadIcon

127

一篇演示如何在 XAML 中将日期值作为属性值传递的文章。

引言

本文将展示如何在 XAML 中将 DateTime 值传递给属性。

背景

最近,我需要一个封装的、可重用的“关于框”控件,我可以在多个 Silverlight 应用程序中使用。 然后我编写了一个用户控件来达到这个目的。 AboutBox 显示按应用程序版本分组的应用程序版本,以及该版本中包含的更改/更新列表。 示例如下所示

About Box example

虽然 AboutBox 用户控件的使用和实现超出了本文的范围,但 AboutBox 的一项功能是使开发人员能够为产品版本项指定日期。 我通过在 VersionInformation 类中创建一个名为 DateDateTime 属性来为此做准备。 但是,当尝试在使用 AboutBox 用户控件的页面的 XAML 中为此属性指定值时,我遇到了问题,如下所示

<applesControls:AboutBox Margin="5">
    <applesControls:AboutBox.ItemsSource>
        <applesClasses:VersionInformation VersionNumber="1.0.0.0" Date="12 January 2009">
        <applesClasses:VersionInformation.Changes>
            <applesClasses:Change Item="First release." />
        </applesClasses:VersionInformation.Changes>
        </applesClasses:VersionInformation>
    </applesControls:AboutBox.ItemsSource>
</applesControls:AboutBox>

我意识到 XAML 本身不知道如何将字符串转换为 DateTime 值,并且将 Date 属性设置为 Date="12 January 2009" 会导致运行应用程序时出现 AG_E_UNKNOWN_ERROR XAML 分析器错误。

值得庆幸的是,有一种方法可以解决这个问题。 答案在于 TypeConverter

Using the Code

示例代码已编写为 Visual Studio 2008 SP1 解决方案,其中包含三个项目

  1. 46ApplesAboutBox
  2. 这是一个 Silverlight 3 应用程序,由一个 MainPage.xaml 组成,用于显示 AboutBox 用户控件。

  3. 46ApplesAboutBox.Common
  4. 一个 Silverlight 3 类库,包含以下类声明

    • VersionInformation
    • DateTypeConverter
    • AboutBox 用户控件
  5. 46ApplesaboutBox.Web
  6. 一个 ASP.NET Web 应用程序,用于托管 46ApplesAboutBox Silverlight 应用程序。

运行演示

  • 将包含该解决方案的 zip 存档 (46ApplesAboutBox.zip) 解压缩到磁盘。
  • 使 46ApplesaboutBox.Web 成为启动项目。
  • 46ApplesAboutBoxTestPage.aspx 设置为启动页。

编写自定义 TypeConverter

为了让我们在 XAML 中将 DateTime 值作为自定义属性传递,我们需要编写一个 TypeConverter。 对于 AboutBox 项目,我创建了一个名为 DateTypeConverter 的类,该类继承自 TypeConverter 类并覆盖其中的方法。 被覆盖的更有趣的方法之一是 ConvertFrom 方法。

public override object ConvertFrom(ITypeDescriptorContext context, 
                       CultureInfo culture, object value)
{
    if (value.GetType() == typeof(string))
    {
        try
        { return DateTime.Parse(value.ToString()); }
        catch
        { throw new InvalidCastException(); }
    }
    return base.ConvertFrom(context, culture, value);
}

此方法负责将指定的日期 string 表示形式转换为预期的 DateTime 值。

还有一件事要做。 我们需要告诉 VersionInformation 类中的 Date 属性,我们想要使用自定义类型转换器,它将执行从 stringDateTime 的转换。 这是通过将 TypeConverter 属性添加到 Date 属性来实现的,如下所示

[TypeConverter(typeof(DateTypeConverter))]
public DateTime Date
{
    get { return (DateTime)GetValue(_dateProperty); }
    set { SetValue(_dateProperty, value); }
}

现在,这将允许我们将“12 January 2009”字符串传递到 Date 属性中,它将被转换为并被视为 DateTime 值。

© . All rights reserved.