如何从Window.Resources以编程方式向x:Array添加新项目

时间:2019-04-08 07:46:30

标签: c# wpf

我有以下XAML代码:

<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>

我知道我可以通过c#的这两行来访问此数组:

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

但是如果我想以编程方式向x:Array添加新字符串怎么办?

我已经尝试过:arrayXAML.Items.Add("hello");,但是当我如上所述使用“ FindRescource”时,它似乎不起作用。有没有办法向该数组添加项目?

1 个答案:

答案 0 :(得分:1)

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}"/>