views:

533

answers:

1

Hello All

I am trying to bind a combo box with some data. The problem is that I have the data in the combo box like this:

                            <ComboBox>
                                <ComboBoxItem>Item 1</ComboBoxItem>
                                <ComboBoxItem>Item 2</ComboBoxItem>
                                <ComboBoxItem>Item 3</ComboBoxItem>
                                <ComboBoxItem>Item 4</ComboBoxItem>
                                <ComboBoxItem>Item 5</ComboBoxItem>
                            </ComboBox>

when the form with the combo box is loaded I have a Resource loaded that has an int that I want to bind it to this combo box. So if that int is 1 i want the combo box to show Item 1 etc. and when I change the item of the combo box I want to update that int accordingly.

Is there a way to bind this resource to the combo box to achive that?

Thank you in advance

+5  A: 

Here is a complete XAML sample on how to do this:

<Window x:Class="WpfApplication1.Window1"
    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="Window1">
    <Window.Resources>
        <sys:Int32 x:Key="TheIndex">2</sys:Int32>
    </Window.Resources>
    <ComboBox SelectedIndex="{Binding Source={StaticResource TheIndex}, Mode=OneWay}">
        <ComboBoxItem>One</ComboBoxItem>
        <ComboBoxItem>Two</ComboBoxItem>
        <ComboBoxItem>Three</ComboBoxItem>
        <ComboBoxItem>Four</ComboBoxItem>
    </ComboBox>
</Window>

Note the following:

  • the sys XML namespace is declared as a mapping to the System CLR namespace in the mscorlib assembly
  • the Binding on SelectedIndex is set to OneWay because it defaults to TwoWay, which makes no sense when binding directly to a resource

HTH, Kent

Kent Boogaart
Hello KentThanks for your replyI am fearly new to wpf programming and I need some more explenation to the snipset you posted.How do I declare the <sys:Int32 x:Key="TheIndex">2</sys:Int32>and how is that bound to my resource?Thank you again
Taonias
@Taonias: no problem. I've updated my post with a complete, working example.
Kent Boogaart