Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an Array declared in a XAML resource

Tags:

c#

xaml

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?

like image 360
TheEvilPenguin Avatar asked Jun 03 '26 15:06

TheEvilPenguin


1 Answers

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

like image 170
Anton Tykhyy Avatar answered Jun 06 '26 05:06

Anton Tykhyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!