I am learning WPF and am trying to create my first UserControl. My UserControl consists of
- StackPanel
- StackPanel contains a Label and TextBox
I am trying to create two Dependency Properties
- Text for the Label
- Orientation for the StackPanel - The orientation will affect the position of the Label and TextBox effectively
I have successfully created a Text dependency property and bind it to my UserControls . But when I created the Orientation property, I seem to get following error in get property
The as operator must be used with a reference type or nullable type ('System.Windows.Controls.Orientation' is a non-nullable value type)
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); }
}
Appreciate your help.
Edit: I changed the code as below and it seem to work as expected. But is this the correct way to solve the problem?
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); }
}
The error message says it all. The as operator can only be used with a Type that is nullable (reference type, or Nullable<T>),
because it will return either the value cast, or null.
What you're trying to use it on is an enumeration.
Just use a regular cast:
get { return (System.Windows.Controls.Orientation) GetValue(OrientationProperty); }
Reasons why:
- You define a default value in your
DependencyProperty.Register
call, eliminating any default null value - Your DependencyProperty is
typeof(Orientation)
, which doesn't allow for nulls - Your class's property definition is
Orientation
, which doesn't allow for nulls - Any attempt to set an invalid value via direct calls to
SetValue(OrientationProperty, null)
will receive an exception, so your property getter won't ever see a null value even by a naughty user of it.
精彩评论