【问题标题】:Why does setting a default value on an enum dependency property fail in WinRT?为什么在 WinRT 中为枚举依赖属性设置默认值会失败?
【发布时间】:2012-10-30 23:18:10
【问题描述】:

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

编译成功,但是当我尝试在 XAML 中使用该对象时,我收到“Specified Cast is not Valid”错误,并且我的对象上有蓝色下划线。

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); }
    }

【问题讨论】:

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


    【解决方案1】:

    尝试使用“1”作为值。枚举的底层类型是 Int32(默认),也许它需要一个整数作为默认值。

    【讨论】:

    • 这似乎有效。 FWIW - 当我在 XAML 中从默认值更改为非默认值时,我收到一个简短的 com 错误,但是当我编译时它消失了。可能相关,也可能不相关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多