为什么在枚举依赖项属性上设置默认值会在WinRT中失败?

时间:2012-11-11 03:39:11

标签: xaml windows-runtime dependency-properties winrt-xaml

我正在尝试使用枚举作为依赖项属性的类型,但默认设置似乎都失败。

编译成功,但是当我尝试在XAML中使用该对象时,我得到“指定的强制转换无效”错误以及我的对象上的蓝色下划线。

VS2012使用WinRT。

我做错了什么?

以下是我正在使用的代码:

public class WheelPanel : Panel
{
    public enum ItemAlignmentOptions
    {
        Left, Center, Right
    }

    /// <summary>
    /// Identifies the <see cref="ItemAlignment" /> dependency property.
    /// </summary>

    // This fails using null

    //public static readonly DependencyProperty ItemAlignmentProperty = DependencyProperty.Register(
    //    ItemAlignmentPropertyName,
    //    typeof(ItemAlignmentOptions),
    //    typeof(WheelPanel),
    //    new PropertyMetadata(null,new PropertyChangedCallback(ItemAlignmentChanged)));

    // This fails using a default value

    //public static readonly DependencyProperty ItemAlignmentProperty = DependencyProperty.Register(
    //    ItemAlignmentPropertyName,
    //    typeof(ItemAlignmentOptions),
    //    typeof(WheelPanel),
    //    new PropertyMetadata(ItemAlignmentOptions.Center,new PropertyChangedCallback(ItemAlignmentChanged)));

    // This works!
    public static readonly DependencyProperty ItemAlignmentProperty = DependencyProperty.Register(
        ItemAlignmentPropertyName,
        typeof(ItemAlignmentOptions),
        typeof(WheelPanel),
        new PropertyMetadata(new PropertyChangedCallback(ItemAlignmentChanged)));

    /// <summary>
    /// The <see cref="ItemAlignment" /> dependency property's name.
    /// </summary>
    public const string ItemAlignmentPropertyName = "ItemAlignment";

    /// <summary>
    /// Gets or sets the value of the <see cref="ItemAlignment" />
    /// property. This is a dependency property.
    /// </summary>
    public ItemAlignmentOptions ItemAlignment
    {
        get { return (ItemAlignmentOptions)GetValue(ItemAlignmentProperty); }
        set { SetValue(ItemAlignmentProperty, value); }
    }

1 个答案:

答案 0 :(得分:1)

尝试使用'1'作为值。枚举的基础类型是Int32(默认情况下),也许它需要一个整数作为默认值。