How to make ListBox editable when bound to a List?

前端 未结 4 972
清酒与你
清酒与你 2020-12-03 13:26

Edit: The basic problem is binding a List to ListBox(or any other control). So I am editing the question.

I bound a list of string to a ListBox as b

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 13:58

    The DataContext of each ListBoxItem is the string itself, so the path of your binding is empty (.). TwoWay and OneWayToSource bindings require a path, since you can't just replace the current DataContext. So you need to wrap your string in an object that exposes the string as a property:

    public class StringItem
    {
        public string Value { get; set; }
    }
    

    Expose the strings as a list of StringItem:

    public partial class MainWindow : Window
    {
        List _nameList = null;
    
        public List NameList
        {
            get
            {
                if (_nameList == null)
                {
                    _nameList = new List();
                }
                return _nameList;
            }
            set
            {
                _nameList = value;
            }
        }
        public MainWindow()
        {
            NameList.Add(new StringItem { Value = "test1" });
            NameList.Add(new StringItem { Value = "test2" });
            InitializeComponent();
        }
    

    And bind to the Value property:

    
        
            
                
            
        
    
    

    Note that StringItem will also need to implement INotifyPropertyChanged so that bindings are automatically updated. You should also expose the list as an ObservableCollection rather than a List

提交回复
热议问题