rudeboy rudeboy - 21 days ago 6
C# Question

Bind CheckListBox to ViewModel

I'm using a CheckListBox from the WPF Toolkit and trying to bind it to my ViewModel. In addition to obtaining the selected values from the control I would also like to be able to reset it through a button click which would clear any selections. I'm stuck on how to bind the selected or checked state of each item in the collection, but if my whole approach is off I would appreciate some direction on that as well.

I've created a simple class with a string descriptor and a Boolean property that I planned to use to indicate the state of each checkbox...

public class DrugInfluence : INotifyPropertyChanged
{
public string Impairment { get; set; }
private bool isChecked;

public bool IsChecked
{
get { return isChecked; }
set
{
if(isChecked != value)
{
isChecked = value;
OnPropertyChanged("IsChecked");
}
}
}

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}


A collection of DrugInfluence objects in the ViewModel called ImpairmentList that I want to bind to the CheckListBox control iteself...

public List<DrugInfluence> ImpairmentList
{
get
{
return impairmentList;
}
set
{
if(impairmentList != value)
{
impairmentList = value;
NotifyPropertyChanged("ImpairmentList");
}
}
}


A list to hold the selected items

public List<DrugInfluence> SelectedImpairments
{
get { return selectedImpairments; }
set
{
if (selectedImpairments != value)
{
selectedImpairments = value;
NotifyPropertyChanged("SelectedImpairments");
}
}
}


And the XAML I'm using to bind the ViewModel to the CheckListBox control...

<sdk:CheckListBox Margin="6"
ItemsSource="{Binding ImpairmentList}"
DisplayMemberPath="Impairment"
SelectedMemberPath="IsChecked"
SelectedItemsOverride="{Binding SelectedImpairments, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
</sdk:CheckListBox>

Answer

Is this the control you are using? If so, it looks like SelectedMemberPath is the property you want to bind to. You will also need to raise an event when the IsChecked property changes if you want to check/uncheck programatically. For instance,

 public class DrugInfluence : INotifyPropertyChanged
    {
        public string Impairment { get; set; }

        private bool _isChecked;
        public bool IsChecked 
        { 
            get{ return _isChecked;}
            set
            {
                if (_isChecked!= value)
                {
                    _isChecked= value;
                    OnPropertyChanged("IsChecked");
                }
            }; 
        }
    }

And then implement the rest of the INotifyPropertyChanged members