简体   繁体   English

在 DataContext C# WPF 之外使用绑定的 CheckBox 值

[英]Use bound CheckBox value also outside of the DataContext C# WPF

I want to use the status of a checkbox in another class.我想在另一个 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.这是我的代码示例: 请注意:所有绑定、OnPropertyChanged 和具有 Icommand 的 RelayCommand 均已正确实现并且可以正常工作。 But not in here, to make it easier to read.但不是在这里,以使其更易于阅读。

MainWindow XAML:主窗口 XAML:

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

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

HomeViewModel (DataContext): HomeViewModel(数据上下文):

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

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?如何在其他类中使用 IsSelected 的状态?

Unfortunately I can't access it directly (I don't know why).不幸的是,我无法直接访问它(我不知道为什么)。

Thanks for your help.谢谢你的帮助。

It looks like you are creating new instance of HomeViewModel in your Class1.看起来您正在 Class1 中创建 HomeViewModel 的新实例。 Is that what you intended to do?那是你打算做的吗? If you want to work with the HomeViewModel you are creating Class1 from you need to pass the reference to it.如果您想使用 HomeViewModel 来创建 Class1,您需要将引用传递给它。 Something like this:像这样的东西:

HomeViewModel:主视图模型:

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

Class1:第一类:

//constructor
public Class1(HomeViewModel _viewModel)
{
    viewModel = _viewModel;
}

HomeViewModel viewModel;

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

Sorry if I missed the point here.对不起,如果我错过了这里的重点。

EDIT: Assuming that your MainWindowViewModel is actually HomeViewModel编辑:假设您的 MainWindowViewModel 实际上是 HomeViewModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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