1

I have this XAML code:

<Window.Resources>
    <x:Array x:Name="arrayXAML" x:Key="WordList" Type="sys:String">
      <sys:String>Abraham</sys:String>
      <sys:String>Xylophonic</sys:String>

      <sys:String>Yistlelotusmoustahoppenfie</sys:String>
      <sys:String>Zoraxboraxjajaja</sys:String>
    </x:Array>
</Window.Resources>

I know that I can access this array by both of these lines of c#:

Object res1 = this.Resources["WordList"];
wordList = this.FindResource("WordList") as string[];

But what about if I want to add a new string to the x:Array programmatically?

I have tried: arrayXAML.Items.Add("hello"); but it doesn't seem to work when I then use the "FindRescource" as shown above. Is there a way to add items to this array?

Rekshino
  • 6,954
  • 2
  • 19
  • 44
  • You could instead use an observablecollection https://social.technet.microsoft.com/wiki/contents/articles/26200.wpf-dynamicresource-observablecollection.aspx – Andy Apr 08 '19 at 13:24

1 Answers1

2

In XAML x:Array is represented with ArrayExtension class.

See x:Array on MSDN:

In the .NET Framework XAML Services implementation, the handling for this markup extension is defined by the ArrayExtension class.

It is important to understand, that what you have/get in/from your ResourceDictionary is not an ArrayExtension but string[].
So run-time changes on arrayXAML you will not see in the ResourceDictionary.

You can't add new element to the string[], see link, but what you can is to set new value in the ResourceDictionary for key WordList:

var sarr = this.Resources["WordList"] as string[];
var newSarr = new string[sarr.Length+1];
for (int i = 0; i < sarr.Length; i++)
{
    newSarr[i] = sarr[i];
}

newSarr[newSarr.Length-1] = "New string from code behind";          
this.Resources["WordList"] = newSarr;

Remark: Since you are modifing the resource, then do use a DynamicResource:

<ListBox ItemsSource="{DynamicResource WordList}"/>
Rekshino
  • 6,954
  • 2
  • 19
  • 44
  • 1
    @mm8 You can't add an element to the __existing__ instance of array. Resize method creates new instance and copy elements to it. Just not with `for` loop. – Rekshino Apr 08 '19 at 14:34
  • Your are wrong. See [source code](https://referencesource.microsoft.com/#mscorlib/system/array.cs,71074deaf111c4e3) – Rekshino Apr 08 '19 at 14:37
  • You are absolutely correct. It does create a copy. My bad. (+1) – mm8 Apr 08 '19 at 14:41
  • @mm8 I admit, that it is a vile trap with changing only of the local variable by Array.Resize. – Rekshino Apr 08 '19 at 14:48