Binding a WPF ComboBox to a custom list

后端 未结 4 555
暗喜
暗喜 2020-11-22 11:59

I have a ComboBox that doesn\'t seem to update the SelectedItem/SelectedValue.

The ComboBox ItemsSource is bound to a property on a ViewModel class that lists a bunch

相关标签:
4条回答
  • 2020-11-22 12:31

    To bind the data to ComboBox

    List<ComboData> ListData = new List<ComboData>();
    ListData.Add(new ComboData { Id = "1", Value = "One" });
    ListData.Add(new ComboData { Id = "2", Value = "Two" });
    ListData.Add(new ComboData { Id = "3", Value = "Three" });
    ListData.Add(new ComboData { Id = "4", Value = "Four" });
    ListData.Add(new ComboData { Id = "5", Value = "Five" });
    
    cbotest.ItemsSource = ListData;
    cbotest.DisplayMemberPath = "Value";
    cbotest.SelectedValuePath = "Id";
    
    cbotest.SelectedValue = "2";
    

    ComboData looks like:

    public class ComboData
    { 
      public int Id { get; set; } 
      public string Value { get; set; } 
    }
    
    0 讨论(0)
  • 2020-11-22 12:32

    I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.

    <ComboBox Name="CategoryList"
              DisplayMemberPath="CategoryName"
              SelectedItem="{Binding Path=CategoryParent}"
              SelectedValue="{Binding Path=CategoryParent.ID}"
              SelectedValuePath="ID">
    

    See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.

    0 讨论(0)
  • 2020-11-22 12:35

    I had a similar issue where the SelectedItem never got updated.

    My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.

    public override bool Equals(object obj)
    {
        return this.Id == (obj as MyCustomObject).Id;
    }
    
    0 讨论(0)
  • 2020-11-22 12:41

    You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

    Have you set the DataContext to your ConnectionViewModel object?

    I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

    Here is my XAML content:

    <Window x:Class="WpfApplication6.Window1"
            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>
        <StackPanel>
            <Button Click="Button_Click">asdf</Button>
            <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                      DisplayMemberPath="Name"
                      SelectedValuePath="Name"
                      SelectedValue="{Binding Path=PhonebookEntry}" />
        </StackPanel>
    </Grid>
    </Window>
    

    And here is my code-behind:

    namespace WpfApplication6
    {
    
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
                ConnectionViewModel vm = new ConnectionViewModel();
                DataContext = vm;
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
            }
        }
    
        public class PhoneBookEntry
        {
            public string Name { get; set; }
    
            public PhoneBookEntry(string name)
            {
                Name = name;
            }
    
            public override string ToString()
            {
                return Name;
            }
        }
    
        public class ConnectionViewModel : INotifyPropertyChanged
        {
            public ConnectionViewModel()
            {
                IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
                list.Add(new PhoneBookEntry("test"));
                list.Add(new PhoneBookEntry("test2"));
                _phonebookEntries = new CollectionView(list);
            }
    
            private readonly CollectionView _phonebookEntries;
            private string _phonebookEntry;
    
            public CollectionView PhonebookEntries
            {
                get { return _phonebookEntries; }
            }
    
            public string PhonebookEntry
            {
                get { return _phonebookEntry; }
                set
                {
                    if (_phonebookEntry == value) return;
                    _phonebookEntry = value;
                    OnPropertyChanged("PhonebookEntry");
                }
            }
    
            private void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
            public event PropertyChangedEventHandler PropertyChanged;
        }
    }
    

    Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

    Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

    System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

    Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

    0 讨论(0)
提交回复
热议问题