Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked ListBox (WPF)

I can't get a checked ListBox to work.

My business object (it's a private/nested class, hence the lower-case)

    class shop : System.ComponentModel.INotifyPropertyChanged
    {
        internal int id;
        string _name;
        internal string name
        {
            get { return _name; }
            set
            {
                _name = value;
                if (PropertyChanged != null) PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("name"));
            }
        }

        bool _selected;
        internal bool selected
        {
            get { return _selected; }
            set
            {
                _selected = value;
                if (PropertyChanged != null) PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("selected"));
            }
        }
    }

My XAML:

<ListBox ItemsSource="{Binding}" Grid.Row="1" HorizontalAlignment="Stretch" Margin="10,0,10,0" Name="lbSelectedShops" VerticalAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Width="Auto" Content="{Binding Path=name}" IsChecked="{Binding Path=selected, Mode=TwoWay}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>                                
</ListBox>

Databinding in code behind is very simple:

lbSelectedShops.ItemsSource = _shops;

where _shops is an ObservableCollection<shop> (containing two elements).

What I get is two blank checkboxes in the listbox (no captions, and both ticked off, even though selected is set to true for all items in the ItemsSource).

I'm really frustrated already and I'm sure it must be something very trivial. What is wrong here?

like image 209
Konrad Morawski Avatar asked Aug 29 '26 12:08

Konrad Morawski


1 Answers

It's not working because your properties are internal and for Databinding you need public properties.
From MSDN (Binding Sources Overview):

You can bind to public properties, sub-properties, as well as indexers, of any common language runtime (CLR) object. The binding engine uses CLR reflection to get the values of the properties. Alternatively, objects that implement ICustomTypeDescriptor or have a registered TypeDescriptionProvider also work with the binding engine.

like image 95
nemesv Avatar answered Sep 01 '26 11:09

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!