3

My goal is to retrieve an ObservableCollection<Color> out of a XAML resource file, but I'm using .NET 3.5 so I can't directly declare the generic type in XAML. My current solutions is to declare a Color array in XAML:

<x:Array Type="Color" x:Key="ColourPickerStandardColours">
    <Color>#974806</Color>
    <Color>#FF0000</Color>
    <Color>#FFC000</Color>
    ...
    <Color>#7030A0</Color>
</x:Array>

and retrieve it in code:

var standardColours = new ObservableCollection<Color>(
    (Color[])TryFindResource("ColourPickerStandardColours"));

When I try to run this though, I get this exception:

InvalidCastException
Unable to cast object of type 'System.Windows.Markup.ArrayExtension' to type
    'System.Windows.Media.Color[]'.

ArrayExtension has IList Items, but I need the generic IEnumerable<T> to construct an ObservableCollection<T>. I think I could use ProvideValue(IServiceProvider), but I'm not sure what I should pass to it.

Am I doing something wrong, or just missing something obvious?

2
  • 2
    Just use Items.Cast<Color> (). Commented Dec 13, 2012 at 21:42
  • ...And I feel like an idiot now. Thanks. If you want to post it as an answer I'll accept it. Commented Dec 13, 2012 at 21:45

2 Answers 2

4

WPF uses an untyped collection there. Just use Items.Cast<Color> ().

Sign up to request clarification or add additional context in comments.

Comments

-1

Cast to ArrayExtension, and your values are in the Items property

3 Comments

Unfortunately I need a generic collection to construct the ObservableCollection, and Items is just IList. Anton Tykhyy was correct with .Cast<Color>().
@TheEvilPenguin why do you need a generic collection? You don't even need to load into an ObservableCollection. You can bind to the IList directly - it isn't going to change.
The control I'm using takes an ObservableCollection<ColorItem> (ColorItem is easy to construct from Color). I included notes about why I couldn't use .Items in the question, but didn't think I would need to go into massive detail describing the reasons behind my requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.