Search code examples
c#.netwpflistboxchecklistbox

How to bind a list of custom object as source to listbox?


I am tying to bind a list of custom objects as a source to listbox where my listbox has user template as

    <DataTemplate x:Key="UserTemplate1" >
      <StackPanel Orientation="Horizontal">
        <TextBlock  Name="vmname" Text="{Binding }" Width="100"/>
        <CheckBox Name="cb" IsChecked="{Binding ischeck}"/>
       </StackPanel>
    </DataTemplate>

and I used this template as datatype for listbox

      <ListBox Name="listbox3" Visibility="Hidden" Height="134" Width="156" Margin="515,82,62,104" IsSynchronizedWithCurrentItem="True" ItemTemplate="{StaticResource UserTemplate1}"  />

I have list of objects of custom datatype

    class item{
         string name;
         bool val; 
         } 

I am not able to bind this list to listbox. i want to bind list in such a way that whenever change is made to checkbox in list, they should reflect in list of objects(item).

       listbox3.itemsource = list_items

This does not work for me

Here, I am not able to bind listbox3 to the list of objects of class checkvm.


Solution

  • You problem is that the changes (which are reflected in the instance of the item class) are not automatically reflected to another view / binding to an item of the list. If you want to notify the second view that a property of the item instance has changed it has to implement INotifyPropertyChanged. The easiest way is achieve that is to use a MVVM-framework. Your item class should extend the ViewModel class which implements the change notification.

    example:

    public class Item : ViewModelBase
    {
    
        private string _Name;
        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                if (_Name != value)
                {
                    _Name = value;
                    RaisePropertyChanged(() => this.Name);
                }
            }
        }
    
        private bool _IsSelected;
        public bool IsSelected
        {
            get
            {
                return _IsSelected;
            }
            set
            {
                if (_IsSelected != value)
                {
                    _IsSelected = value;
                    RaisePropertyChanged(() => this.IsSelected);
                }
            }
        }
    }