Reputation: 163
I want to create an array resource of colors in XAML where each color is defined as a dynamic resource. I think that it can be done, but I can't figure out the syntax.
I have tried this:
<x:Array Type="Color" x:Key="Colors">
<Color>
<DynamicResource ResourceKey="BasicBlueColor" />
</Color>
</x:Array>
But it doesn't work, because dynamic resource can only be assigned to dependency property.
And this just simply doesn't work, but I think it describes well what I am trying to do:
<x:Array Type="Color" x:Key="Colors">
<Color>{DynamicResource BasicRedColor}</Color>
</x:Array>
Clarification:
Edit 2: I was under impression that the resources are defined as static or dynamic and that they must be used as defined. My thanks to @Sham for explaining it to me.
Upvotes: 0
Views: 1351
Reputation: 930
Use ResourceDictionary
to place multiple resources.
You may create one ResourceDictionary
with name "ApplicationNameColors" and use these keys wherever required. Don't forget to add this to application/windows/etc resources
before using.
DynamicResource
is very different mechanism than the things you are talking about. It's recomended to use DynamicResource
when your style is dependent on windows setting because DynamicResource
may cost the application performance.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1">
<SolidColorBrush x:Key="Color1" Color="#555555" />
<SolidColorBrush x:Key="Color2" Color="#555555" />
<SolidColorBrush x:Key="Color3" Color="#555555" />
<SolidColorBrush x:Key="Color4" Color="#555555" />
<SolidColorBrush x:Key="Color5" Color="#555555" />
</ResourceDictionary>
Upvotes: 1
Reputation: 169200
You could reference the Color
resources using StaticResource
. This works:
<Color x:Key="BasicRedColor">Red</Color>
<Color x:Key="BasicGreenColor">Red</Color>
<x:Array Type="Color" x:Key="Colors">
<StaticResource ResourceKey="BasicRedColor" />
<StaticResource ResourceKey="BasicGreenColor" />
</x:Array>
If you want to to be able to switch colours at runtime, you will have to replace or modify the Color
objects in the array programmatically.
An array is an array that may or may not contain some elements. It's not some kind of dependency object.
Upvotes: 3
Reputation: 9461
It's impossible, since dynamic resource should be used for dependency property in objects derived from DependencyObject, but x:Array is not a dependencyobject, this is what error says:
A 'DynamicResourceExtension' cannot be used within a 'ArrayList' collection. A 'DynamicResourceExtension' can only be set on a DependencyProperty of a DependencyObject.
Upvotes: 1