【发布时间】:2010-05-04 16:10:30
【问题描述】:
我正在学习 WPF 并尝试创建我的第一个 UserControl。我的 UserControl 包括
- 堆栈面板
- StackPanel 包含一个标签和文本框
我正在尝试创建两个依赖属性
- 标签文本
- 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