mardi 2 juillet 2019

WPF two way binding not working on CheckBox

I can't manage to make my two way binding with the checkbox work.

The checkbox item source is PRESTAZIONI and contains a bool field called "Check_Status" with default 0.

The Data Binding code (DataClassesDataContext) is generated by the LINQtoSQL drag and drop, so it should be fine. It has all the ViewModel parts of this solution WPF CheckBox TwoWay Binding not working.

I have this XAML code:

<StackPanel Grid.Column="3" Grid.Row="3">
        <ListBox Name ="listPrest" Height="91" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Name="chkPrest" Width="220" IsChecked="{Binding Path=Check_Status, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                        <TextBlock TextWrapping="Wrap">
                            <TextBlock.Text>
                                <MultiBinding StringFormat="{}{0} ({1})">
                                    <Binding Path="Nome" />
                                    <Binding Path="Code" />
                                </MultiBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </CheckBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>

In the code of the view, I inizialize the source of the checkboxes like this:

public partial class InsertServiceView : UserControl
{
    DataClassesDataContext db = new DataClassesDataContext();
    IQueryable<PRESTAZIONI> prest = null;
    public InsertServiceView()
    {
        InitializeComponent();
        UpdatePrestList();
    }

    private void UpdatePrestList()
    {
        if (prest != null)
        {
            foreach (PRESTAZIONI p in prest)
            {
                p.Check_Status = false;
            };
        } 
        else 
        {
              prest = from p in db.PRESTAZIONI select p;
        }
        listPrest.ItemsSource = prest.ToList();
    }

    private void ButtonSave_Click(object sender, RoutedEventArgs e)
    {
        using (DataClassesDataContext db = new DataClassesDataContext())
        {

            if (prest.Where(p => p.Check_Status == true).Count() == 0)
            {
                MessageBox.Show("Non hai selezionato correttamente le prestazioni.");
                return;
            }

And even if I check the checkboxes this last if keeps returning true.

I update the value of check_status setting all false because I use it also in other forms and I want them to be all false when I open this one.

I've seen a lot of questions similar to mine and applied all the solutions but still it is not working. Any suggestion would be very appreciated. Sorry for the poor english.




Aucun commentaire:

Enregistrer un commentaire