我的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