开发者

DependencyProperty Orientation problem

开发者 https://www.devze.com 2022-12-28 22:21 出处:网络
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 learning WPF and am trying to create my first UserControl. My UserControl consists of

  1. StackPanel
  2. StackPanel contains a Label and TextBox

I am trying to create two Dependency Properties

  1. Text for the Label
  2. 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:

  1. You define a default value in your DependencyProperty.Register call, eliminating any default null value
  2. Your DependencyProperty is typeof(Orientation), which doesn't allow for nulls
  3. Your class's property definition is Orientation, which doesn't allow for nulls
  4. 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消