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?

1

1 Answer 1

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}"/>
Sign up to request clarification or add additional context in comments.

4 Comments

@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.
Your are wrong. See source code
You are absolutely correct. It does create a copy. My bad. (+1)
@mm8 I admit, that it is a vile trap with changing only of the local variable by Array.Resize.

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.