flyNflip
flyNflip

Reputation: 489

How to bind to a dependency property with an unknown type

I have created a user control that has a dependency property that I need to bind with multiple types. In other words, it has a dependency property named "DataSource." However, the developer could bind a type

ObservableCollection<MyCustomType>

or

ObservableCollection<ObservableCollection<MyCustomType>>. 

In the user control's code, I want to execute two separate code chunks based on which type is detected as not null or something equivalent. I've been searching for examples but I think my perspective on how this should be done may be misplaced. Instruction or direction would be appreciated.

Upvotes: 1

Views: 465

Answers (1)

Lukazoid
Lukazoid

Reputation: 19416

Declare your dependency property as a property of type object.

Then when the value of this property changes, you can perform different functionality depending upon the value of it, i.e.

public static readonly DependencyProperty DataSourceProperty = 
    DependencyProperty.Register("DataSource", typeof(object), typeof(MyControl), new PropertyMetaData(OnDataSourceChanged));

private static void OnDataSourceChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    var newValue = e.NewValue;

    if(newValue == null)
        return;

    var asSingleLevel = newValue as ObservableCollection<MyCustomType>;
    if(asSingleLevel != null)
    {
        // Do work for single level
    }
    else
    {
        var asDoubleLevel = newValue as ObservableCollection<ObservableCollection<MyCustomType>>;

        if(asDoubleLevel != null)
        {
            // Do work for double level
        }
    }
}

Upvotes: 1

Related Questions