Search This Blog

Thursday, May 14, 2015

ComboBox Binding WPF C# Example

WPF > Controls > ItemsControl > ComboBox

ComboBox control  allows a user to select an item from a dropdown list.



Example

ComboBox bind to Student view model and display selected value to  TextBlock. 

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ComboBox ItemsSource="{Binding Path=Students}"
                  DisplayMemberPath="LastName"
                  SelectedValuePath="FirstName"
                  SelectedValue="{Binding Path=Student}" Margin="10,28,337,263"
                  Name="cboStudent"
                  />
        <Label Content="Student" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Top"/>
        <TextBlock HorizontalAlignment="Left" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top"
                  Text="{Binding ElementName=cboStudent, Path=SelectedValue}" Width="170"/>
    </Grid>
</Window>

namespace WpfApplication1
{
    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class StudentViewModel : INotifyPropertyChanged
    {
        private readonly CollectionView students;
        private string student;

        public StudentViewModel()
        {
            IList<Student> list = new List<Student>();
            list.Add(new Student() { FirstName = "Bill" , LastName = "Jones" });
            list.Add(new Student() { FirstName = "John", LastName = "Water" });
            students = new CollectionView(list);
        }

        public string Student
        {
            get { return student; }
            set
            {
                if (student == value) return;
                student = value;
                OnPropertyChanged("student");
            }
        }
        private void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public CollectionView Students
        {
            get { return students; }
        }

    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            StudentViewModel viewModel = new StudentViewModel();
            DataContext = viewModel;

        }
    }
}