我有三个类MainWindow.xaml.cs,Download.cs和ContentFetcher.cs。 Download.cs具有属性设置和获取方法。我正在更新MainWindow.xaml.cs中的download.cs的属性。我想在Download.cs中获取属性的值虽然它没有给我更新的属性值。所有三个类的代码如下:
Download.cs
private int _DownloadLevel = 0;
public int DownloadLevel
{
get { return _DownloadLevel; }
set
{
if (_DownloadLevel == value)
return;
_DownloadLevel = value;
this.OnPropertyChanged("DownloadLevel");
}
}
private bool _IsAudio = false;
public bool IsAudio
{
get { return _IsAudio; }
set
{
if (_IsAudio == value)
return;
_IsAudio = value;
this.OnPropertyChanged("IsAudio");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
在ContentFetcher.cs
中 Download download = new Download();
MessageBox.Show(download.DownloadLevel.ToString()); // Output is 0, it should 05
MessageBox.Show(download.IsAudio.ToString()); // Output is false while it should be true
请指导我如何在ContentFetcher.cs中获取更新的属性值
答案 0 :(得分:0)
您正在Download
中创建ContentFetcher
的新实例。它没有引用您在原始实例中设置的值,因此您获得的只是int
/ bool
类型的默认值。
我没有看到您在实例化ContentFetcher
的位置,但是您需要传入对您创建的第一个Download
实例的引用。
public class ContentFetcher
{
Download download;
public ContentFetcher(Download download)
{
this.download = download;
}
public void SomeOtherMethod()
{
// Don't create a new instance of Download - use the original instance
// Download download = new Download();
MessageBox.Show(download.DownloadLevel.ToString()); // Output is 0, it should 05
MessageBox.Show(download.IsAudio.ToString());
}
...
...
}