Reputation: 1074
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));
}
}
Upvotes: 1
Views: 355
Reputation: 169400
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.
Upvotes: 3