如何使Silverlight自定义控件的属性可数据绑定?

3

我创建了一个自定义的Silverlight控件,由两个日期选择器和一个组合框组成。 我想让组合框可数据绑定,我知道我需要使用DependencyProperty。 但我不确定如何构建它。 这是我目前的代码:

#region ItemsSource (DependencyProperty)

    /// <summary>
    /// ItemsSource to bind to the ComboBox
    /// </summary>
    public IList ItemsSource
    {
        get { return (IList)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(int), typeof(DateRangeControl),
          new PropertyMetadata(0));

    #endregion

问题在于,我看到的所有示例都是针对简单属性(如Text或Background),这些属性期望的是字符串、整数或颜色。由于我正在尝试绑定到组合框的ItemsSource,它期望的是IEnumerable,我不知道如何构建此属性。因此,我使用了IList。
请问有人能告诉我我是否走在正确的道路上,并给我一些指导吗?谢谢。
2个回答

3

我看到你发布的代码存在问题。在注册DP时,实例访问器和类型需要保持一致。如果将typeof(int)更改为typeof(IList),你现有的代码应该可以正常工作。

但是通常最好使用满足属性要求的最低级别类型。基于此,如果您想创建集合属性,请使用IEnumerable,除非您真的需要IList提供的功能。


1

你不能只是使用这个吗?

        public IEnumerable ItemsSource
    {
        get
        {
            return (IEnumerable)GetValue(ItemsSourceProperty);
        }
        set
        {
            SetValue(ItemsSourceProperty, value);
        }
    }

    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(DateRangeControl), new PropertyMetadata(null));

IEnumerable 可在 System.Collections.Generic 中找到。


当我这样做时,get和set根本没有被调用。 - Doguhan Uluca
2
get和set不需要被调用。属性的实际值会自动存储在其他位置。这就是为什么在属性内部使用GetValue和SetValue来从DependancyProperty系统存储的位置检索值。 - Sekhat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接