0
votes

I am pretty new to C# WPF, so please bear with my question. I have two listboxes (listbox1 and listbox2) where the items in listbox1 will be added or removed during runtime through user input. I want the listbox2 to display its listboxitem accordingly through binding method.

For example, if listbox1 has 5 items initially, i want the listbox2 to display the same 5 items. If items in listbox1 being added or removed in runtime, I want the listbox2 to display the same data (items) as listbox1.

Can someone give me a tip? Thanks in advance.

1
Bind both listboxes to the same list in your modelSayse

1 Answers

0
votes

I know little about your case but lets say you have the following datamodel holding your data, implementing the INotifyPropertyChangedInterface:

public class A : INotifyPropertyChanged 
{
    public String SomeProperty {....}
    ...
}

Then you have a viewmodel that contains your items, let it inherhit from som baseclass. I reccomend Galasoft MVVM Light and just further extend your needs. OnPropertyChanges invokes INotifyPropertyChanged. I've cut some corners here, anyhow:

public YourViewModel : YourViewModelBase 
{
   private ObservableCollection<A> yourItems_ = new ObservableCollection<A>();
   public ObservableCollection YourItems {
       get { return yourItems_;}
       set { if( yourItems_!=value ) {
               _yourItems = value;
               OnPropertyChanged();
             }
             return _yourItems;
       }

      }
}

Then in your xaml you just bind to the property YourItems and set the displaymember on your datamodel.

 <UserControl.....>
 <UserControl.DataContext><vm:YourViewModel/></UserControl.DataContext>
    <Grid>
      <Grid.RowDefinition="Auto"/>
      <Grid.RowDefinition="Auto"/>
      <Grid.RowDefinition="*"/>
    <Grid/>
    <ListBox Grid.RowDefinition="0" ItemsSource="{Binding YourItems}" DisplayMemberPath="SomeProperty"/>
    <ListBox Grid.RowDefinition="1" ItemsSource="{Binding YourItems}" DisplayMemberPath="SomeProperty"/>
 </UserControl>

Note that you may edit templates to get another visual representation of your items, using DisplayMamberPath will just add it to the listbox presentation as a string, unless you have a class that overrides to .ToString(); method.

If you need filtering of the same itemssource, have a look at ICollectionView.

Hope it helps,

Cheeers,

Stian