mardi 20 avril 2021

WPF two-way binding does not work for checkboxes inside a combobox

I've tried lots of solutions online but I still get this issue. I have a combobox whose item source is a list of customized class. Each element in the source is displayed as a checkbox in the combobox. Now I have a button whose "Click" function is to uncheck all the checkboxes.

The customized class:

    public class LinkObject: INotifyPropertyChanged
    {
        public int index { set; get; }
        public string LO_Name { set; get; }
        private bool _checkStatus { set; get; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Notify(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public bool checkStatus
        {
            get { return _checkStatus; }
            set
            {
                _checkStatus = value;
                Notify("IsChecked");
            }
        }
    }

The XAML:

<ComboBox Name="cbx1" Grid.ColumnSpan="2" HorizontalAlignment="Left" Margin="126,82,0,0" VerticalAlignment="Top" Width="50" Height="20" IsEditable="True" IsTextSearchEnabled="True" StaysOpenOnEdit="True" TextBoxBase.TextChanged="cbx1_TextChanged">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Name="cbk1" IsChecked="{Binding checkStatus, Mode=TwoWay}" CommandParameter="{Binding index}" Checked="chk_Checked"  Unchecked="chk_Unchecked">
                <CheckBox.Content>
                    <TextBlock Text="{Binding LO_Name}"/>
                </CheckBox.Content>
            </CheckBox>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Main function by initialization:

cbx1.ItemsSource = LinkObjectsList_cbx1;

LinkObjectsList_cbx1 is a List<LinkObject>.

The button has a name "clearAllTopView", the click function is:

private void clearAllTopViewBtn_Click(object sender, RoutedEventArgs e)
{
    LinkObjectsList_cbx1.Where(l => l.checkStatus == true).ToList().ForEach(lo => lo.checkStatus = false);
}

But when I click the button, nothing happens. Could someone give me a hint or advice? Thank you.




Aucun commentaire:

Enregistrer un commentaire