Proper use of PropertyChangedTrigger and ChangePropertyAction

后端 未结 3 749
一向
一向 2021-01-16 05:40

I\'m trying to set a default selected value when ItemsSource property changes on my ComboBox

My xaml :



        
3条回答
  •  猫巷女王i
    2021-01-16 06:10

    has in addition to the current answers which led me on the way to my solution what i actually needed to accomplish is retrieving the last selected item when switching between itemsSources (plural)

    from an article i found : "for each ItemsSource binding, a unique CollectionView is generated.."

    i concurred that as long as the view exists each binding would generate its own CollectionView and thus hold a reference to CurrentItem and CurrentPosition if decorated with

    IsSynchronizedWithCurrentItem="True"

    so i created my own ChangePropertyAction Class :

     public class RetriveLastSelectedIndexChangePropertyAction : ChangePropertyAction
     {                
        public int LastSelectedIndex
        {
            get { return (int)GetValue(LastSelectedIndexProperty); }
            set { SetValue(LastSelectedIndexProperty, value); }
        }
    
        public static readonly DependencyProperty LastSelectedIndexProperty =
            DependencyProperty.Register("LastSelectedIndex", typeof(int), typeof(RetriveLastSelectedIndexChangePropertyAction), new UIPropertyMetadata(-1));
    
        protected override void Invoke(object parameter)
        {
            var comboBox = this.AssociatedObject as ComboBox;
            this.SetValue(LastSelectedIndexProperty, comboBox.Items.CurrentPosition);            
        }        
     }
    

    and invoked it using PropertyChangedTrigger as follows :

                                         
           
              
                  
                                      
           
                  
    

    hope this helps if any one needing to retrieve their last selected item with out any messy code in their DataContext , enjoy.

提交回复
热议问题