zync
zync

Reputation: 461

Problem with static data binding in wpf

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

<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

Upvotes: 0

Views: 902

Answers (1)

Aviad P.
Aviad P.

Reputation: 32629

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.

Upvotes: 2

Related Questions