Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. WPF
  4. WPF ComboBox

WPF ComboBox

Scheduled Pinned Locked Moved WPF
wpfhelpcsharpcsswcf
6 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    mark_w_
    wrote on last edited by
    #1

    Good afternoon. I cant seem to get a combobox to select a value using Binding. I have a small example that re-creates the issue, I want the combo to have selected Yellow (_colour is set to that on creation) when it first loads. Hope that makes sense Code is below, just window1 and a class called ViewModel. TIA for any help :) Window1.xaml

    <window x:class="ComboBoxTest.Window1" xmlns:x="#unknown">
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <grid>
    <combobox margin="92,122,66,116">
    ItemsSource="{Binding Path=Colours}"
    DisplayMemberPath="Description"
    SelectedItem="{Binding Path=SelectedColour, Mode=TwoWay}"
    Grid.Column="1"
    Grid.Row="8"
    IsSynchronizedWithCurrentItem="True"

                  />
    </combobox></grid>
    

    </window>

    Window1.xaml.cs

    using System.Windows;

    namespace ComboBoxTest
    {
    /// /// Interaction logic for Window1.xaml
    ///
    public partial class Window1 : Window
    {
    public Window1()
    {
    this.DataContext = new ViewModel();
    InitializeComponent();
    }
    }
    }

    ViewModel.cs

    using System;
    using System.Collections.Generic;
    using System.Windows;

    namespace ComboBoxTest
    {

    public class Colour : IComparable
    {
        public string Description { get; set; }
    
        #region IComparable Members
    
        public int CompareTo(object obj)
        {
            return string.Compare(((Colour) obj).Description, this.Description);
        }
    
        #endregion
    }
    
    public class ViewModel : DependencyObject
    {
        public List<colour> Colours
        {
            get
            {
                List<colour> retval = new List<colour>();
                retval.Add(new Colour { Description = "Blue" });
                retval.Add(new Colour { Description = "Green" });
                retval.Add(new Colour { Description = "White" });
                retval.Add(new Colour { Description = "Yellow" });
                retval.Add(new Colour { Description = "Red" });
                retval.Add(new Colour { Description = "Silver" });
    
    I M 2 Replies Last reply
    0
    • M mark_w_

      Good afternoon. I cant seem to get a combobox to select a value using Binding. I have a small example that re-creates the issue, I want the combo to have selected Yellow (_colour is set to that on creation) when it first loads. Hope that makes sense Code is below, just window1 and a class called ViewModel. TIA for any help :) Window1.xaml

      <window x:class="ComboBoxTest.Window1" xmlns:x="#unknown">
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Window1" Height="300" Width="300">
      <grid>
      <combobox margin="92,122,66,116">
      ItemsSource="{Binding Path=Colours}"
      DisplayMemberPath="Description"
      SelectedItem="{Binding Path=SelectedColour, Mode=TwoWay}"
      Grid.Column="1"
      Grid.Row="8"
      IsSynchronizedWithCurrentItem="True"

                    />
      </combobox></grid>
      

      </window>

      Window1.xaml.cs

      using System.Windows;

      namespace ComboBoxTest
      {
      /// /// Interaction logic for Window1.xaml
      ///
      public partial class Window1 : Window
      {
      public Window1()
      {
      this.DataContext = new ViewModel();
      InitializeComponent();
      }
      }
      }

      ViewModel.cs

      using System;
      using System.Collections.Generic;
      using System.Windows;

      namespace ComboBoxTest
      {

      public class Colour : IComparable
      {
          public string Description { get; set; }
      
          #region IComparable Members
      
          public int CompareTo(object obj)
          {
              return string.Compare(((Colour) obj).Description, this.Description);
          }
      
          #endregion
      }
      
      public class ViewModel : DependencyObject
      {
          public List<colour> Colours
          {
              get
              {
                  List<colour> retval = new List<colour>();
                  retval.Add(new Colour { Description = "Blue" });
                  retval.Add(new Colour { Description = "Green" });
                  retval.Add(new Colour { Description = "White" });
                  retval.Add(new Colour { Description = "Yellow" });
                  retval.Add(new Colour { Description = "Red" });
                  retval.Add(new Colour { Description = "Silver" });
      
      I Offline
      I Offline
      Insincere Dave
      wrote on last edited by
      #2

      The way you have declared SelectedColour isn't right, you don't need a backing field as it that is done automatically. You can either call GetValue/SetValue in the property passing in SelectedColourProperty or implement INotifyPropertyChanged and raise the event in the setter (Then you wouldn't need to inherit from DependencyObject). There may be some other issues as I couldn't test the code atm. http://msdn.microsoft.com/en-us/library/ms750428.aspx http://msdn.microsoft.com/en-us/library/ms229614.aspx

      M 1 Reply Last reply
      0
      • I Insincere Dave

        The way you have declared SelectedColour isn't right, you don't need a backing field as it that is done automatically. You can either call GetValue/SetValue in the property passing in SelectedColourProperty or implement INotifyPropertyChanged and raise the event in the setter (Then you wouldn't need to inherit from DependencyObject). There may be some other issues as I couldn't test the code atm. http://msdn.microsoft.com/en-us/library/ms750428.aspx http://msdn.microsoft.com/en-us/library/ms229614.aspx

        M Offline
        M Offline
        mark_w_
        wrote on last edited by
        #3

        Thanks for your reply, this was a test project and you are right i did not have the Selected Colour correct, i have changed it and it still does not work, so will look at INotifyPropertyChanged, and let you know. Mark

        M 1 Reply Last reply
        0
        • M mark_w_

          Thanks for your reply, this was a test project and you are right i did not have the Selected Colour correct, i have changed it and it still does not work, so will look at INotifyPropertyChanged, and let you know. Mark

          M Offline
          M Offline
          mark_w_
          wrote on last edited by
          #4

          Cant get that working either, If anybody would be able to convert my sample app, i would be greatful

          1 Reply Last reply
          0
          • M mark_w_

            Good afternoon. I cant seem to get a combobox to select a value using Binding. I have a small example that re-creates the issue, I want the combo to have selected Yellow (_colour is set to that on creation) when it first loads. Hope that makes sense Code is below, just window1 and a class called ViewModel. TIA for any help :) Window1.xaml

            <window x:class="ComboBoxTest.Window1" xmlns:x="#unknown">
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Window1" Height="300" Width="300">
            <grid>
            <combobox margin="92,122,66,116">
            ItemsSource="{Binding Path=Colours}"
            DisplayMemberPath="Description"
            SelectedItem="{Binding Path=SelectedColour, Mode=TwoWay}"
            Grid.Column="1"
            Grid.Row="8"
            IsSynchronizedWithCurrentItem="True"

                          />
            </combobox></grid>
            

            </window>

            Window1.xaml.cs

            using System.Windows;

            namespace ComboBoxTest
            {
            /// /// Interaction logic for Window1.xaml
            ///
            public partial class Window1 : Window
            {
            public Window1()
            {
            this.DataContext = new ViewModel();
            InitializeComponent();
            }
            }
            }

            ViewModel.cs

            using System;
            using System.Collections.Generic;
            using System.Windows;

            namespace ComboBoxTest
            {

            public class Colour : IComparable
            {
                public string Description { get; set; }
            
                #region IComparable Members
            
                public int CompareTo(object obj)
                {
                    return string.Compare(((Colour) obj).Description, this.Description);
                }
            
                #endregion
            }
            
            public class ViewModel : DependencyObject
            {
                public List<colour> Colours
                {
                    get
                    {
                        List<colour> retval = new List<colour>();
                        retval.Add(new Colour { Description = "Blue" });
                        retval.Add(new Colour { Description = "Green" });
                        retval.Add(new Colour { Description = "White" });
                        retval.Add(new Colour { Description = "Yellow" });
                        retval.Add(new Colour { Description = "Red" });
                        retval.Add(new Colour { Description = "Silver" });
            
            M Offline
            M Offline
            Mark Salsbery
            wrote on last edited by
            #5

            Does it work if you implement your Colour class something like this?

            public class Colour
            {
                public string Description { get; set; }
            
                public override bool Equals(object obj)
                {
                    return this.Description == (obj as Colour).Description;
                }
            
                public override int GetHashCode()
                {
                    return base.GetHashCode() ^ this.Description.GetHashCode();
                }
            }
            

            ...and your SelectedColour dependency property:

                public static DependencyProperty SelectedColourProperty =
                            DependencyProperty.Register("SelectedColour", typeof(Colour), typeof(ViewModel));
                public Colour SelectedColour
                {
                    get { return (Colour)GetValue(SelectedColourProperty); }
                    set { SetValue(SelectedColourProperty, value); }
                }
            

            Mark Salsbery Microsoft MVP - Visual C++ :java:

            M 1 Reply Last reply
            0
            • M Mark Salsbery

              Does it work if you implement your Colour class something like this?

              public class Colour
              {
                  public string Description { get; set; }
              
                  public override bool Equals(object obj)
                  {
                      return this.Description == (obj as Colour).Description;
                  }
              
                  public override int GetHashCode()
                  {
                      return base.GetHashCode() ^ this.Description.GetHashCode();
                  }
              }
              

              ...and your SelectedColour dependency property:

                  public static DependencyProperty SelectedColourProperty =
                              DependencyProperty.Register("SelectedColour", typeof(Colour), typeof(ViewModel));
                  public Colour SelectedColour
                  {
                      get { return (Colour)GetValue(SelectedColourProperty); }
                      set { SetValue(SelectedColourProperty, value); }
                  }
              

              Mark Salsbery Microsoft MVP - Visual C++ :java:

              M Offline
              M Offline
              mark_w_
              wrote on last edited by
              #6

              Many thanks for your reply. That still does not do what i want, i am starting to think that i am going about this the wrong way :( Put simply what i need is a combobox with a datasource of list of my objects (all the same type). Then when the form loads i want the combobox to have preselected an object of my choice (what ever was saved in xml/db) I am new to wpf and the mvvm pattern, and this is getting a bit frustrating!! ps for info i changed the colour class to the following as the other throw an exception

              public class Colour
              {
                 public string Description { get; set; }   
                  public override bool Equals(object obj)
                  {
                      if(obj.GetType()== typeof(Colour))
                      return this.Description == ((Colour) obj).Description;
              
                      return base.Equals(obj);
                  }       
                  
                  public override int GetHashCode()
                  {
                      return base.GetHashCode() ^ this.Description.GetHashCode();
                  }
              
                 
              }
              
              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups