Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make an List<string> a static resource in xaml?

If I want to bind something like a combobox in the code-behind I have no problem at all. Something like :

List<string> strings = new List<string>();
AddStringsFromDataSourceToList(strings);

comboBox1.ItemSource = strings;

As far as I can tell, there is no quick and dirty way to do this in XAML. For all of the praise wpf is receiving for its super simple databinding, something this simple seems far easier to just do in C#. Is there an easier way to do this than creating DependencyProperty wrappers and adding them as resources without much help from intellisense or all that goes into ObservableCollections? I understand that its not impossible, but I must be missing something if such a simple task seems so in depth...

EDIT: To clarify, adding dynamic Lists is the issue here, not static arrays. It is super easy to add items manually, as many have pointed out.

like image 454
Morgan Herlocker Avatar asked Jan 19 '11 18:01

Morgan Herlocker


People also ask

What is static resource in WPF?

Static Resource - Static resources are the resources which you cannot manipulate at runtime. The static resources are evaluated only once by the element which refers them during the loading of XAML.

Which are valid types of resources in WPF?

WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.


1 Answers

<Window.Resources>
    <x:Array x:Key="strings" Type="sys:String" 
            xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <sys:String>One</sys:String>
            <sys:String>Two</sys:String>
    </x:Array>
    <!-- likewise -->
    <x:Array x:Key="persons" Type="{x:Type local:Person}" 
            xmlns:local="clr-namespace:namespace-where-person-is-defined">
            <local:Person FirstName="Sarfaraz" LastName="Nawaz"/>
            <local:Person FirstName="Prof" LastName="Plum"/>
    </x:Array>
<Window.Resources>


<ComboBox ItemsSource="{StaticResource strings}" />

<ListBox ItemsSource="{StaticResource persons}">
     <ListBox.ItemTemplate>
           <DataTemplate>
               <TextBlock>
                     <Run Text="{Binding FirstName}"/>
                     <Run Text="  "/>
                     <Run Text="{Binding LastName}"/>
               </TextBlock>
           </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>
like image 121
Nawaz Avatar answered Oct 06 '22 01:10

Nawaz