views:

27

answers:

1

Hi. I'm relatively new to wpf and I quite don't understand binding yet.

I want to have several combo boxes in my application with the same items. The basic solution would be to copy paste but that just isn't good practice. So I thought to put a static resource with the content I want and bind all combo boxes to it. It compiles and runs well but the combo box is empty.

Here's the code:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;

<ItemsControl x:Key="Validations">
    <ItemsControl.Items>
        <ComboBoxItem>String</ComboBoxItem>
        <ComboBoxItem>Numeric</ComboBoxItem>
    </ItemsControl.Items>
</ItemsControl>

and here's the combo box:

<ComboBox ItemsSource="{Binding Source={StaticResource Validations}}"/>

I know the solution for this is probably simple but I haven't figured it out yet. I'll keep trying ;)

Thanks

+1  A: 

Make the resource a list of strings, not a visual element, then use the StaticResource extension to assign it to the ItemsSource property, like so:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <x:ArrayExtension x:Key="Data" Type="{x:Type sys:String}">
            <sys:String>String1</sys:String>
            <sys:String>String2</sys:String>
            <sys:String>String3</sys:String>
        </x:ArrayExtension>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <ComboBox ItemsSource="{StaticResource Data}"/>
            <ComboBox ItemsSource="{StaticResource Data}"/>
            <ComboBox ItemsSource="{StaticResource Data}"/>
        </StackPanel>
    </Grid>
</Window>

Note the definition of the xmlns:sys namespace (maps to namespace System in assembly mscorlib) and the use of the x:ArrayExtension element to declare a simply array in XAML.

Aviad P.
Thanks for the help but it didn't work.. It throws an exception:Cannot convert the value in attribute 'ItemsSource' to object of type 'System.Collections.IEnumerable'. 'System.Windows.Markup.ArrayExtension' is not a valid value for property 'ItemsSource'.
zync
This was tried and tested on VS2010 with .NET 4. - Are you using the same?
Aviad P.