我的ViewModel中有一个属性,其值在BackgroundWorker的DoWork方法中更改。当我启动应用程序并单击启动BackgroundWorker的按钮时,我会看到此属性的值如何更改。但是,当我打开一个新窗口时,该属性保留其默认值,即使BackgroundWorker仍在运行,该属性也不会更新。更新WPF中另一个窗口的属性值
她是我的ViewModel代码:
private string currentData;
...
public ViewModel()
{
...
// Property initialised with a default value
currentData = "BackgroundWorker is not running";
...
}
public string CurrentData
{
get { return this.currentData; }
private set
{
if (this.currentData != value)
{
this.currentData = value;
this.RaisePropertyChanged("CurrentData");
}
}
}
private void DoWork(object sender, DoWorkEventArgs e)
{
isUpdating = true;
...
this.CurrentData = "BackgroundWorker is running...";
for (...)
{
...
if(...)
{
this.CurrentData = "value1";
}
else
{
this.CurrentData = "value2";
...
}
}
}
RaisePropertyChanged方法:
<TextBlock Margin="10" MinWidth="250" VerticalAlignment="Center" Text="{Binding CurrentData}" FontSize="12" Foreground="White" HorizontalAlignment="Left" />
BackgroundWorker的:两个窗口(主窗口和newtWindow)
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
XAML代码:
private readonly BackgroundWorker worker;
...
public ImageViewModel()
{
currentData = "BackgroundWorker is not running";
this.worker = new BackgroundWorker();
this.worker.DoWork += this.DoWork;
this.worker.ProgressChanged += this.ProgressChanged;
this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_Completeted);
this.worker.WorkerReportsProgress = true;
}
你能告诉我做错了什么,我该如何解决它?
那里有很多椭圆(...)你看不到类定义, t看到'RaisePropertyChanged'方法,你没有看到任何事件,请提供实际编译的代码,否则几乎不可能发生什么问题 – Sefe
椭圆(...)只代表很多被执行的操作。所以,因为代码很长,所以是 – Guilian
你有Whatevs类的实例A.你正在改变实例A的属性。如果你想要两个窗口显示这个实例A的改变版本,那么这两个窗口必须有实例A的引用。你如何在两个窗口之间共享实例取决于你的设计,谁构造窗户,以及它们是如何构建的。 – Will