WPF: Combobox binding

This entry is part 27 of 54 in the series Learn WPF

In Windows Desktop, ComboBox works just like a drop down list in the web.

Here we illustrate an example where the background color of a canvas is bound to a ComboBox selection.

In this example, I have also used setter property to style the TextBlock, Canvas etc.  This is just like using CSS to style a HTML page.

<Window x:Class="BindControls.MainWindow"
        Title="MainWindow" Height="350" Width="525">
            <Style TargetType="TextBlock">
                <Setter Property="FontSize" Value="16"/>
                <Setter Property="FontWeight" Value="Bold"/>
                <Setter Property="DockPanel.Dock" Value="Top"/>
                <Setter Property="HorizontalAlignment" Value="Center"/>
            <Style TargetType="Canvas">
                <Setter Property="Height" Value="150"/>
                <Setter Property="Width" Value="150"/>
                <Setter Property="Margin" Value="8"/>
                <Setter Property="DockPanel.Dock" Value="Top"/>
            <Style TargetType="ComboBox">
                <Setter Property="Width" Value="60"/>
                <Setter Property="Margin" Value="8"/>
                <Setter Property="DockPanel.Dock" Value="Top"/>

        <Border Margin="10" BorderBrush="Silver" BorderThickness="3" Padding="8">
                <TextBlock>Choose a Color:</TextBlock>
            <ComboBox Name="myBox" SelectedIndex="0">
            <Canvas Background="{Binding ElementName=myBox, Path=SelectedItem.Content}"></Canvas>

using System.Windows;

namespace BindControls
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

When you run the code and changing the ComboBox selection, the canvas color will change according to the selection.  This is done mainly with xaml.

The main line that is performing this trick is:

<Canvas Background="{Binding ElementName=myBox, Path=SelectedItem.Content}"></Canvas>

Each change in the ComboBox selection will update the background color as we have set the Path to SelectedItem.Content of the combo box.




Series Navigation<< WPF: XAML ComboBox
WPF: Adding items to combobox using ObservableCollection >>