gpt4 book ai didi

c# - 绑定(bind)到由在后台工作的线程创建的对象的属性

转载 作者:行者123 更新时间:2023-12-03 10:49:45 25 4
gpt4 key购买 nike

我在我的多线程 WPF 应用程序中使用 MVVM 模式。

现在在我拥有的模型中(我跳过了 INotifyPropertyChanged 接口(interface)的明显实现以使其更清晰):

public class ShallowModel : INotifyPropertyChanged
{
private string _dbState;
public string DbState
{
get { return _dbState; }
set
{
_dbState = value;
OnPropertyChanged("DbState") // ofc there is implementation of this
}
}
private InsideObject _inObject;
public InsideObject InObject
{
get { return _inObject; }
set
{
_inObject = value;
OnPropertyChanged("InObject")
}
}
}

public class InsideModel : INotifyPropertyChanged
{
private string _actState;
public string ActState
{
get { return _actState; }
set
{
_actState= value;
OnPropertyChanged("ActState")
}
}
}

假设我在 View 上有 TextBlocks:
<TextBlock Text={Binding ActObjectState}/>
<TextBlock Text={Binding DbState}/>

现在有一部分有问题的 ViewModel:
public class ViewModel : INotifyPropertyChanged
{
private ShallowModel _model;
public string ActObjectState
{
get
{
if(_model.InObject != null)
return _model.InObject.ActState;
else
return null;
}
}
public string DbState
{
get
{
return _model.DbState;
}
}
}

问题是当后台线程更新 ShallowModel 和/或 InsideModel 的属性时,ActObjectState 和 DbState 没有被更新。我的问题是:
  • 我应该将模型公共(public)属性添加到 ViewModel 并像 {Binding Path=Model.DbState} 这样绑定(bind) View 吗?我认为它破坏了 MVVM 的想法—— View 不应该知道模型。
  • 在用户单击 UI 上的按钮后,ShallowModel 中的 InObject 由新线程创建。因此,当创建 ViewModel 时,InObject 为空。不知何故 - 在它由线程创建之后 - ActObjectState 没有更新。如何让它发挥作用?像 {Binding Path=Model.InObject.ActState} 那样进行绑定(bind)?这意味着 UI 设计师需要了解模型。

  • 谢谢,对不起我的英语

    最佳答案

    我会接受你的建议 1. 这是最简单的方法,我没有看到任何违反 MVVM 模式的行为。

    如果这对您不起作用 - 您必须将 View 相关逻辑放在您的 View 模型中。所以可能有必要让 View 模型监听模型的变化并将这些变化重新抛出(与 View 相关的逻辑) View 。

    使用线程时要注意调度程序的东西,但我想你知道

    关于c# - 绑定(bind)到由在后台工作的线程创建的对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312845/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com