加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

WPF依赖项属性优先级和引用类型默认值

发布时间:2020-12-14 00:50:41 所属栏目:百科 来源:网络整理
导读:如果我创建这样的自定义控件: public class MyControl : ContentControl{ public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register( "Items",typeof(ObservableCollectionobject),typeof(MyControl),new PropertyMetadata(
如果我创建这样的自定义控件:
public class MyControl : ContentControl
{
   public static readonly DependencyProperty ItemsProperty =               
         DependencyProperty.Register(
                "Items",typeof(ObservableCollection<object>),typeof(MyControl),new PropertyMetadata(null));

   public MyControl()
   {   
       // Setup a default value to empty collection
       // so users of MyControl can call MyControl.Items.Add()
       Items = new ObservableCollection<object>();
   }

   public ObservableCollection<object> Items
   { 
      get { return (ObservableCollection<object>)GetValue(ItemsProperty); } 
      set { SetValue(ItemsProperty,value); } 
   } 
}

然后允许用户在Xaml中绑定它,如下所示:

<DataTemplate>
    <MyControl Items="{Binding ItemsOnViewModel}"/>
</DataTemplate>

然后绑定永远不会起作用!这是由于Dependency Property Precedence,它将CLR Set值置于模板绑定之上!

所以,我理解为什么这不起作用,但我想知道是否有解决方案.对于只想以编程方式添加Items的MyControl的懒惰使用者,可以为新的ObservableCollection提供ItemsProperty的默认值,同时允许My Control的MVVM高级用户通过DataTemplate绑定到同一属性吗?

这适用于Silverlight& WPF.风格中的DynamicResource setter看起来像是一个解决方案但对Silverlight不起作用:(

更新:

我可以确认SetCurrentValue(ItemsProperty,new ObservableCollection< object>());正是我想要的 – 在WPF中.它写入默认值,但可以通过模板绑定覆盖它.任何人都可以建议Silverlight等效吗?说起来容易做起来难! :■

另一个更新:

显然,你可以使用值强制模拟.NET3.5中的SetCurrentValue,并且可以使用这些技术在Silverlight中模拟值强制.也许这里有一个(冗长的)解决方法.

SetCurrentValue workaround for .NET3.5 using Value Coercion
Value Coercion workaround for Silverlight

你不能只指定依赖属性的默认属性:
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
        "Items",typeof(CaseDetailControl),new PropertyMetadata(new ObservableCollection<object>()));

还是我错过了你的追求?

编辑:

啊……在那种情况下如何在getter上检查null?:

public ObservableCollection<object> Items
    {
        get
        {
            if ((ObservableCollection<object>)GetValue(ItemsProperty) == null)
            {
                this.SetValue(ItemsProperty,new ObservableCollection<object>());
            }

            return (ObservableCollection<object>)GetValue(ItemsProperty);
        }

        set
        {
            this.SetValue(ItemsProperty,value);
        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读