简体   繁体   中英

Get bool value of Checkbox in wpf with binding in mvvm C#

I have the following code:

ViewModel:

DownloadDeviceViewModel : ViewModelBase
{
    private bool _isSelected;

    public bool isSelected
    {
        get
        {
            return _isSelected;
        }
        set
        {
            if (_isSelected != value)
            {
                _isSelected = value;
                OnPropertyChanged();

            }
        }
    }

    public void Method()
    {
        if(isSelected)
        {

        }
    }
}

XAML:

<CheckBox Content="Checkbox" IsChecked="{Binding isSelected, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

The method onPropertyChanged is in the ViewModelBase. I have not inserted this to make it easier to read.

Every time when I call the value of "isSelected" in a method, IsSelected returns wrong. Even though I selected the checkbox and the value of isSelected was set to true.

But in the method the value changes back to false.

What did I implement incorrectly that the value is always changed to false?

Thank you all

your ViewModel needs to be INotifyPropertyChanged :

DownloadDeviceViewModel : ViewModelBase, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string nomPropriete)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(nomPropriete));
    }
    private bool _isSelected;

    public bool isSelected
    {
        get
        {
            return _isSelected;
        }
        set
        {
            if (_isSelected != value)
            {
                _isSelected = value;
                NotifyPropertyChanged("isSelected");
            }
        }
    }

    public void Method()
    {
        if(isSelected)
        {

        }
    }
}

Then in your XAML, UpdateSourceTrigger is no needed

<CheckBox Content="Checkbox" IsChecked="{Binding isSelected}"/>

is enough

In your setter, remove the "if" conditional, you don't need it. That might be causing your problems.

        set
        {
                _isSelected = value;
                OnPropertyChanged();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM