【问题标题】:DependencyProperty Orientation problemDependencyProperty 方向问题
【发布时间】:2010-05-04 16:10:30
【问题描述】:

我正在学习 WPF 并尝试创建我的第一个 UserControl。我的 UserControl 包括

  1. 堆栈面板
  2. StackPanel 包含一个标签和文本框

我正在尝试创建两个依赖属性

  1. 标签文本
  2. StackPanel 的方向 - 方向将有效影响 Label 和 TextBox 的位置

我已成功创建 Text 依赖属性并将其绑定到我的 UserControls 。但是当我创建 Orientation 属性时,我似乎在 get 属性中出现以下错误

as 运算符必须与引用类型或可为空的类型一起使用('System.Windows.Controls.Orientation' 是不可为空的值类型)

public static DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(System.Windows.Controls.Orientation), typeof(MyControl), new PropertyMetadata((System.Windows.Controls.Orientation)(Orientation.Horizontal)));
public Orientation Orientation
{
    get { return GetValue(OrientationProperty) as System.Windows.Controls.Orientation; }
    set { SetValue(OrientationProperty, value); }
}

感谢您的帮助。

编辑: 我更改了如下代码,它似乎按预期工作。但这是解决问题的正确方法吗?

public Orientation Orientation  
{
        get 
        {
            Orientation? o = GetValue(OrientationProperty) as System.Windows.Controls.Orientation?;
            if (o.HasValue)
            {
                return (System.Windows.Controls.Orientation)o.Value;
            }
            else
            {
                return Orientation.Horizontal;
            }
        }
        set { SetValue(OrientationProperty, value); }
    }      

【问题讨论】:

    标签: wpf user-controls dependency-properties


    【解决方案1】:

    错误消息说明了一切。 as 运算符只能与可为空的类型(引用类型或 Nullable<T>), 一起使用,因为它将返回值强制转换或 null。

    您尝试使用的是枚举。

    只需使用常规演员:

    get { return (System.Windows.Controls.Orientation) GetValue(OrientationProperty); } 
    

    原因:

    1. 您在DependencyProperty.Register 调用中定义一个默认值,消除任何默认空值
    2. 您的 DependencyProperty 是 typeof(Orientation),这不允许空值
    3. 你的类的属性定义是Orientation,它不允许空值
    4. 任何通过直接调用 SetValue(OrientationProperty, null) 来设置无效值的尝试都会收到异常,因此您的属性 getter 将永远不会看到 null 值,即使是顽皮的用户。

    【讨论】:

    • 我刚刚添加了我在代码中所做的更改。你能评论一下我的改变吗?我应该直接施法还是使用我使用的方法?
    • 只需使用演员表。您的属性不允许可为空值。 (您没有将依赖属性定义为 Orientation?,也没有将属性本身定义为 Orientation?,因此不需要 as 关键字。特别是因为您在 Dependency Property 定义中提供了 Orientation.Horizo​​ntal 的默认值,所以没有定义可空性。
    • 谢谢亚当。我使用“as”是因为我在一篇关于 Dependency Property 的文章中看到了它,并且它们在 String 返回类型上使用了 as。我已经投票给你的答案,现在我会标记是这样。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多