WPF Combo Box Binding
I am trying to bind a combo box with some data. The problem is I have data in a combo box:
<ComboBox>
<ComboBoxItem>Item 1</ComboBoxItem>
<ComboBoxItem>Item 2</ComboBoxItem>
<ComboBoxItem>Item 3</ComboBoxItem>
<ComboBoxItem>Item 4</ComboBoxItem>
<ComboBoxItem>Item 5</ComboBoxItem>
</ComboBox>
when a form with a combo box is loaded, I have a resource loaded that has an int that I want to bind to that combo box. So if this int is 1, I want the combo box to display Item 1, etc., and when I change the item in the combo box, I want to update it accordingly.
Is there a way to link this resource to a combo box to achieve this?
Thank you in advance
+2
source to share
1 answer
Here's a complete XAML example 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>
Please note the following:
- the XML namespace is
sys
declared as a mapping to theSystem
CLR namespace in the mscorlib assembly -
Binding
on isSelectedIndex
set toOneWay
because it defaults toTwoWay
, which makes no sense when binding directly to a resource
+7
source to share