【问题标题】:Use bound CheckBox value also outside of the DataContext C# WPF在 DataContext C# WPF 之外使用绑定的 CheckBox 值
【发布时间】:2020-10-11 02:36:02
【问题描述】:

我想在另一个类中使用复选框的状态。 不幸的是,这并不完全奏效。

这是我的代码示例: 请注意:所有绑定、OnPropertyChanged 和具有 Icommand 的 RelayCommand 均已正确实施并且可以正常工作。 但这里没有,为了便于阅读。

主窗口 XAML:

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

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

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();
}

第一类:

HomeViewModel viewModel = new HomeViewModel();

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

    }
}

如何在其他类中使用 IsSelected 的状态?

很遗憾,我无法直接访问它(我不知道为什么)。

感谢您的帮助。

【问题讨论】:

  • 'IsSelected' 在 MainWindowViewModel 中而不是在 HomeViewModel 中。您可以在 HomeViewModel 类的构造函数中传递 MainWindowViewModel 对象,然后访问它,

标签: c# wpf checkbox binding


【解决方案1】:

看起来您正在 Class1 中创建 HomeViewModel 的新实例。那是你打算做的吗? 如果您想使用 HomeViewModel 来创建 Class1,您需要将引用传递给它。像这样的:

HomeViewModel:

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

第一类:

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

HomeViewModel viewModel;

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

对不起,如果我错过了这里的重点。

编辑:假设您的 MainWindowViewModel 实际上是 HomeViewModel

【讨论】:

    猜你喜欢
    • 2011-10-17
    • 2010-12-02
    • 1970-01-01
    • 2023-03-16
    • 2018-10-16
    • 2016-03-10
    • 2012-11-05
    • 2021-07-19
    • 2013-02-02
    相关资源
    最近更新 更多