简体   繁体   中英

NotifyPropertyChanged not firing

I am trying to capture the SelectedItem for a ListBox when then data template click event is triggered for the Button . I put a breakpoint in the notifypropertychanged event handler, but it never triggers. What am I doing wrong here?

xaml:

   <ListBox x:Name="lstbox_playerContainer"
       ItemsSource="{Binding ChildObjectOC}"  
       SelectedItem="{Binding SelectedChildObject, Mode=TwoWay}">
       <ListBox.ItemTemplate>
           <DataTemplate>
               <Button Name="btn_childButton" Click="btn_childButton_Click"/>                                        
           </DataTemplate>
        </ListBox.ItemTemplate>
   </ListBox>

c#:

public partial class PlayerCrowdPromptPage: INotifyPropertyChanged {

     public PlayerCrowdPromptPage() {
          InitializeComponent();
          DataContext = this;
     }

    private ObservableCollection<PlayerCrowdObjectBO> childObjectOC = new ObservableCollection<PlayerCrowdObjectBO>();
    public ObservableCollection<PlayerCrowdObjectBO> ChildObjectOC {
        get {
            return childObjectOC;
        }
        set {
            childObjectOC = value;
        }
    }

     private PlayerCrowdObjectBO selectedChildObject;
     public PlayerCrowdObjectBO SelectedChildObject {
         get { return selectedChildObject; }
         set {
               selectedChildObject = value;
               OnPropertyChanged("SelectedChildObject");
         }
    }

    public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName) {
            if (PropertyChanged != null){
               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Clicking on the Button won't automatically select the corresponding item. You may select it programmatically in the event handler though:

private void btn_childButton_Click(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    ListBoxItem lbi = lstbox_playerContainer.ItemContainerGenerator.ContainerFromItem(btn.DataContext) as ListBoxItem;
    lbi.IsSelected = true;
}

This should set the SelectedChildObject property and raise the PropertyChanged event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM