【问题标题】:Use Dependency Property in code behind在后面的代码中使用依赖属性
【发布时间】:2013-02-28 12:34:00
【问题描述】:

如何在我的 CodeBehind 中使用定义的 DependencyProperty?

这是我的 DependencyProperty:

    ItemContainerProperty = DependencyProperty.Register("ItemContainer",
                      typeof(ObservableCollection<Item>), typeof(Manager));
    }


    public ObservableCollection<Item> ItemContainer
    {
        get { return (ObservableCollection<Item>)GetValue(ItemContainerProperty); }
        set { SetValue(ItemContainerProperty, value); }
    }

当我这样做时:

for (int i = 0; i <= ItemContainer.Count - 1; i++)
{
}

我收到以下错误消息:内部异常:对象引用未设置为对象的实例。

如何在我的代码中使用该属性?

【问题讨论】:

  • 你初始化ItemContainer了吗?它是否绑定到某些 UI 元素?调试器说什么?
  • @makc 我必须如何初始化 ItemContainer?该属性未绑定到 UI 元素。调试器说在 for 循环中 ItemContainer 为空
  • 那么你就知道为什么不能使用它了,你的属性应该有数据/被初始化数据应该代表一些业务逻辑
  • 好的,这就是错误的问题。你知道一个很好的例子吗?我怎样才能绑定到这个依赖属性?这样我就可以使用:

标签: wpf dependency-properties


【解决方案1】:

如果您不打算为 DependencyProperty 定义默认值,那么您需要在某个时候设置它,它的默认值为 null。

   public partial class MainWindow : Window
    {
        public ObservableCollection<string> Items
        {
            get { return (ObservableCollection<string>)GetValue(ItemsProperty); }
            set { SetValue(ItemsProperty, value); }
        }
        public static readonly DependencyProperty ItemsProperty =
            DependencyProperty.Register("Items", typeof(ObservableCollection<string>), typeof(MainWindow));

        public MainWindow()
        {
            InitializeComponent();

            Items = new ObservableCollection<string>();
        }
    }

如果你不想这样做,那么你可以在依赖属性声明中定义默认值。

   public partial class MainWindow : Window
    {
        public ObservableCollection<string> Items
        {
            get { return (ObservableCollection<string>)GetValue(ItemsProperty); }
            set { SetValue(ItemsProperty, value); }
        }
        public static readonly DependencyProperty ItemsProperty =
            DependencyProperty.Register("Items", typeof(ObservableCollection<string>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<string>()));

        public MainWindow()
        {
            InitializeComponent();
        }
    }

【讨论】:

  • 请注意,在第二个示例中将 DP 中的引用类型默认为非 null 可能会引入非常奇怪的错误,因为 WPF 尝试在属性的所有用户之间共享单个集合(例如派生类)在大多数情况下,第一个示例更可取。
  • 我什至会说第二个例子在除了非常特殊的情况下都是无效的。你通常应该从不这样做。
  • @Clemens 你有什么提示吗,为什么我无法注意到 typ observablecollection 的依赖属性何时被绑定更新? propertychange 事件有什么要实现的吗?
  • 您必须使用 PropertyMetadata 注册一个 PropertyChangedCallback,如 this answer 中所示您上一个问题。我强烈推荐阅读关于Custom Dependency Properties的文章。
  • 如果您想知道何时从集合中插入或删除某些内容,那么您需要订阅它的 CollectionChanged 事件。
猜你喜欢
  • 1970-01-01
  • 2011-02-02
  • 2013-12-02
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多