更新第二类中第一类的属性,并在第三类中获取更新值

时间:2014-02-02 22:10:26

标签: c# properties return-value

我有三个类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中获取更新的属性值

1 个答案:

答案 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());
    }

    ...
    ...
}