WPF dependency property precedence & reference type Default Values

前端 未结 2 1754
暗喜
暗喜 2020-12-12 05:16

If I create a custom control like this:

public class MyControl : ContentControl
{
   public static readonly DependencyProperty ItemsProperty =                       


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 05:50

    Can't you just specify the default property of the dependency property:

      public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
            "Items",
            typeof(ObservableCollection),
            typeof(CaseDetailControl),
            new PropertyMetadata(new ObservableCollection()));
    
    
    

    or am I missing what you are after?

    Edit:

    ah... in that case how about checking for null on the getter?:

        public ObservableCollection Items
        {
            get
            {
                if ((ObservableCollection)GetValue(ItemsProperty) == null)
                {
                    this.SetValue(ItemsProperty, new ObservableCollection());
                }
    
                return (ObservableCollection)GetValue(ItemsProperty);
            }
    
            set
            {
                this.SetValue(ItemsProperty, value);
            }
        }
    
        

    提交回复
    热议问题