Answer the question
In order to leave comments, you need to log in
Why do I get the previous selected item from the SelectedItem Listbox?
I have a listbox:
<ListBox ItemsSource="{Binding Notes}"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Name="NoteList"
SelectedItem="{Binding SelectedNote}"
>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="#FFD7B4F3" >
<TextBlock Text="{Binding Title}" FontSize="15" Margin="2"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding ActivatePanelCommand}" CommandParameter="{Binding SelectedNote}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
class MainVM : INotifyPropertyChanged
{
static public ApplicationContext DB { get; private set; }
IEnumerable<Note> notes;
Note selectedNote;
public IEnumerable<Note> Notes
{
get { return notes; }
set
{
notes = value;
OnPropertyChanged();
}
}
public Note SelectedNote
{
get { return selectedNote; }
set
{
selectedNote = value;
OnPropertyChanged();
}
}
public RelayCommand ActivatePanelCommand
{
get
{
return activatePanelCommand ??
(activatePanelCommand = new RelayCommand((selectedItem) =>
{
Note note = selectedItem as Note;
if(note != null)
{
MessageBox.Show(note.Title);
}
}));
}
public MainVM()
{
CurrentContentVM = new WriteNoteVM();
DB = new ApplicationContext();
DB.Notes.Load();
Notes = DB.Notes.Local.ToBindingList();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
Answer the question
In order to leave comments, you need to log in
I'm not an expert, but it's possible that the GotFocus event fires before the SelectedItem is assigned a value.
You can decide like this.
In addition to the interactivity library, include the interactions library:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei ="http://schemas.microsoft.com/expression/2010/interactions"
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<ei:CallMethodAction MethodName="NoteList_GotFocus"
TargetObject="{Binding }"/>
</i:EventTrigger>
</i:Interaction.Triggers>
public void NoteList_GotFocus(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is ListBoxItem lvi)
{
Note note = lvi.DataContext as Note;
MessageBox.Show(note.Title);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question