MVVM: Binding to List IsSelected while tracking IsSynchronizedWithCurrentItem

后端 未结 2 1537
小鲜肉
小鲜肉 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条回答
  •  -上瘾入骨i
    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()
                {
                    new Item {Name = "Foo"},
                    new Item {Name = "Bar"}
                };
    
            foreach ( Item anItem in Items )
            {
                anItem.PropertyChanged += OnItemIsSelectedChanged;
            }
        }
    
        public ObservableCollection 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));
            }
        }
    }
    

提交回复
热议问题