Reputation:
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
Upvotes: 3
Views: 3757
Reputation: 4528
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.
Upvotes: 3
Reputation: 805
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
Upvotes: 1