【发布时间】:2012-09-09 20:18:59
【问题描述】:
我有一堂这样写的课
public class AudioPlayer : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
[...]
private static AudioPlayer instance = new AudioPlayer();
public static AudioPlayer Instance { get { return instance; } }
private Track currentTrack = null;
// the pointer to the current track selected
// it is useful to retrieve its new position when playlist got updates
public Track CurrentTrack { get { return currentTrack; }
private set
{
currentTrack = value;
NotifyPropertyChanged();
}
}
public class Track : ICloneable
{
public string Title { get; set; }
}
这是 xaml:
<StackPanel DataContext="{Binding Source={x:Static audiocontroller:AudioPlayer.Instance}}">
<Label Name="lbl_bind" Content="{Binding CurrentTrack.Title}"></Label>
<Button Name="btn" Click="btn_Click" Height="20" ></Button>
</StackPanel>
代码有效!
现在我希望使用 ModelView 控制器来组建 AudioPlayer。 如何做到这一点?
【问题讨论】:
-
这个类不是静态的。你为什么说静态类? “公司”是什么意思?
-
它是静态的,因为这个私有静态 AudioPlayer 实例 = new AudioPlayer();不是静态的类是 Track,但此时我对如何处理 mvvm 有点困惑。我会编写一个应该处理 AudioPlayer 的类,并从该类中删除所有 NotifyPropertyChanged,因为“CurrentTrack”是模型,而不是 ModelView
-
这是一个静态字段,不是静态类。
-
您将
DataContext(数据层)设置为静态实例,但数据层应该是动态的。您的应用程序是您的 ViewModel,而不是您的视图,因此静态DataContext表示静态应用程序。最好在应用程序第一次启动时创建AudioPlayer的新实例,并将其设置为应用程序的DataContext。您可以在应用程序中使用静态组件,但不要让整个应用程序保持静态。 -
瑞秋,你的意思是这样的吗?
标签: c# wpf mvvm datacontext inotifypropertychanged