MVVM: Binding to List IsSelected while tracking IsSynchronizedWithCurrentItem

后端 未结 2 1536
小鲜肉
小鲜肉 2021-02-03 16:13

I\'m tracking ListView selection changes in an MVVM design by binding to IsSelected. I also need to track the current item by enabling IsSynchronizedWithCurrentItem.

I

相关标签:
2条回答
  • 2021-02-03 16:26

    I cannot offer a direct fix for your problem. However, I do have a solution that will work.

    What you can do is introduce a second property on your View Model called 'SelectedItem' that will hold a reference to the Item that is selected in your ListView. In addition, in your View Model you listen for the PropertyChanged event. If the associated Property Name is IsSelected then you update the SelectedItem property to be the sender of that event (the Item that now has IsSelected = true). You can then bind the SelectedItem property of the ListView to the property of the same name of the ViewModel class.

    My code for the revised ViewModel class is below.

    public class ViewModel : INotifyPropertyChanged
    {
        private Item _selectedItem;
    
        public ViewModel()
        {
            Items = new ObservableCollection<Item>()
                {
                    new Item {Name = "Foo"},
                    new Item {Name = "Bar"}
                };
    
            foreach ( Item anItem in Items )
            {
                anItem.PropertyChanged += OnItemIsSelectedChanged;
            }
        }
    
        public ObservableCollection<Item> Items { get; private set; }
    
        public Item SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                // only update if the value is difference, don't
                // want to send false positives
                if ( _selectedItem == value )
                {
                    return;
                }
    
                _selectedItem = value;
                OnPropertyChanged("SelectedItem");
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void OnItemIsSelectedChanged(object sender, PropertyChangedEventArgs e)
        {
            if ( e.PropertyName != "IsSelected" )
            {
                return;
            }
    
            SelectedItem = sender as Item;
        }
    
        private void OnPropertyChanged(string propertyName)
        {
            if ( PropertyChanged != null )
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-03 16:26

    The issue seems to happen when you bind to a listbox's IsSelected and use SelectionMode='Single'

    I found that changing the SelectionMode = 'Multiple' and then just added logic to the ViewModel to ensure that there was ever only one item with IsSelected set to true worked.

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