You can bind the selected combox value to a dependency property. For example, here is a window with the dependency property "CurrentTag":
public partial class Window1 : Window { public Window1() { InitializeComponent(); } public override void OnApplyTemplate() { base.OnApplyTemplate(); CurrentTag = "4"; } public static readonly DependencyProperty CurrentTagProperty = DependencyProperty.Register( "CurrentTag", typeof(string), typeof(Window1), new PropertyMetadata("1")); public string CurrentTag { get { return (string)this.GetValue(CurrentTagProperty); } set { this.SetValue(CurrentTagProperty, value); } } }
and in xaml:
<Window x:Class="WpfComboboxBinding.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="100" Width="300" x:Name="window1"> <StackPanel VerticalAlignment="Center"> <ComboBox Name="myMenu" SelectedValue="{Binding ElementName=window1, Path=CurrentTag, Mode=TwoWay}" SelectedValuePath="Tag"> <ComboBoxItem Content="Question 1" Tag="1" /> <ComboBoxItem Content="Question 2" Tag="2" /> <ComboBoxItem Content="Question 3" Tag="3" /> <ComboBoxItem Content="Question 4" Tag="4" /> </ComboBox> </StackPanel> </Window>
Then, to change the selected item, you simply change the value of the property, as in the above example (CurrentTag = "4";)
Jem source share