【发布时间】:2011-09-28 08:46:04
【问题描述】:
我为新手问题道歉,但我正在努力解决这个问题。我定义了以下 TextBlock:
<TextBlock Text="{Binding Source={x:Static local:DeviceManager.Instance},
Path=Player.CurrentArtist}"></TextBlock>
DeviceManager 是一个单例,用作其他类的外观。例如,Player 是一个类型为 IPlayer 的属性,它表示一个音乐播放应用程序。我希望 TextBlock 显示当前正在播放的艺术家,它会在 Player.CurrentArtist 属性中定期更新。
不幸的是,当 CurrentArtist 属性更新时,我无法更新 TextBlock。 DeviceManager 和 IPlayer 都实现了 INotifyPropertyChanged,但是当我单步执行应用程序时,DeviceManager 没有附加事件处理程序。
有没有人建议如何在保留单例外观的同时更新文本块?
下面是 DeviceManager 和 IPlayer 子类中 INotifyPropertyChanged 成员的代码:
public sealed class DeviceManager : INotifyPropertyChanged
{
// Singleton members omitted
public IPlayer Player
{
get { return player; }
set
{
this.player = value;
player.PropertyChanged += new PropertyChangedEventHandler(device_PropertyChanged);
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void device_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(sender, e);
}
}
#endregion
}
class MediaPlayer : IPlayer
{
private string artist;
private string title;
public event PropertyChangedEventHandler PropertyChanged;
public void Play(string artist, string title)
{
this.artist = artist;
this.title = title;
OnPropertyChanged("Player:Song");
}
private void OnPropertyChanged(string p)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(p));
}
}
public string CurrentTitle
{
get { return title; }
}
public string CurrentArtist
{
get { return artist; }
}
}
【问题讨论】: