我在我的多线程 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 没有被更新。我的问题是:
谢谢,对不起我的英语
最佳答案
我会接受你的建议 1. 这是最简单的方法,我没有看到任何违反 MVVM 模式的行为。
如果这对您不起作用 - 您必须将 View 相关逻辑放在您的 View 模型中。所以可能有必要让 View 模型监听模型的变化并将这些变化重新抛出(与 View 相关的逻辑) View 。
使用线程时要注意调度程序的东西,但我想你知道
关于c# - 绑定(bind)到由在后台工作的线程创建的对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312845/