I’m trying to bind two ListBoxes:
<ListBox SelectionChanged="lbApplications_SelectionChanged"
ItemsSource="{Binding Path=Applications,
UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
<ListBox DisplayMemberPath="Message"
ItemsSource="{Binding Path=Events,
UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
Applications and Events are public properties in Window class.
I set DataContext to this to both list boxes and implement INotifyPropertyChanged in Window class:
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
And then after adding new item to Applications or Events I call:
NotifyPropertyChanged("Events");
NotifyPropertyChanged("Applications");
The issue is that ListBox is loaded only one time. What am I doing wrong?
Let’s just look at one of the ListBoxes, since they’re both the same, basically.
The code we’re concerned about is this:
Since you’re new to WPF, let me say you probably don’t need
UpdateSourceTriggerorModein there, which leaves us with this:You mentioned that Applications is a public property in your code-behind. You need it to be a
DependencyProperty, and you need it to fire events when it changes — most people use an ObservableCollection for this.So your code-behind will have something like this:
Then, where you want to add it, you’ll do something like this:
Finally, for the “simple” binding syntax to work in the XAML, I usually change the
DataContextin my Window (or the root Control element for the file, whatever I’m working in) toYour Applications box will update automatically.