views:

1550

answers:

3

Hello, I have created a custom silverlight control, which consists of two date pickers, and a combobox. I would like to make the combobox data-bindable and I know I need to make use of a DependencyProperty. What I am not sure of is exactly how to build it. Here is the code that I have:

#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

The problem is that all the samples I have seen are for simple properties like Text or Background wich expect either a string, int, or color. Since I am trying to bind to the combobox ItemsSource, it expects a IEnumerable, I did not know how to build the property for this. I used IList.

Can someone please let me know if I am on the right path and give me some pointers? Thanks

A: 

Can't you just use this?

     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 can be found in System.Collections.Generic

When I do this, get and set aren't called at all.
duluca
get and set don't need to get called. The actual value of the property is stored else where automatically. Which is why GetValue and SetValue is used inside the property to retrieve the value from where ever the DependancyProperty system stores it.
Sekhat
+1  A: 

I see a problem with the code you posted. The instance accessor and the type defined in your registration of the DP need to agree. Your existing code should work if you change typeof(int) to typeof(IList).

But it is typically best practice to use the lowest level type that satisfies the requirements of the property. Based on that, if you want to create a collection property, use IEnumerable unless you really need functionality provided by IList.

markti
A: 

How do you bind this to the actual combobox?

Brandon