简体   繁体   中英

WPF Combo Box Binding

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM