samedi 20 juin 2020

Use binded CheckBox value also outside of the DataContext C# WPF

I want to use the status of a checkbox in another class. Unfortunately, this does not quite work.

Here is my code example: Please note: All Bindings, OnPropertyChanged and the RelayCommand, which has the Icommand, were implemented correctly and work. But not in here, to make it easier to read.

MainWindow XAML:

<CheckBox Content="Select or not" IsChecked="{Binding IsSelected}"/>

<Button Content="Test" Command="{Binding ButtonCommand}">

MainWindowViewModel (DataContext):

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


public RelayCommand ButtonCommand { get; private set; }

public HomeViewModel()
{
    InitCommands();
}


private void InitCommands()
{
    ButtonCommand = new RelayCommand(DoJob);
}

private void DoJob(object sender)
{
    Class1 class1 = new Class1();
    class1.Method();
}

Class1:

HomeViewModel viewModel = new HomeViewModel();

public void Method()
{
    if (viewModel.IsSelected)
    {

    }
}

How can I use the status of IsSelected in other classes?

Unfortunately I can't access it directly (I don't know why).

Thanks for your help.




Aucun commentaire:

Enregistrer un commentaire