C# 如何使用静态类实现MVVM
我有一节课是这样写的C# 如何使用静态类实现MVVM,c#,wpf,mvvm,datacontext,inotifypropertychanged,C#,Wpf,Mvvm,Datacontext,Inotifypropertychanged,我有一节课是这样写的 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
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”是您的“ViewModel”,您可以这样实现:
<UserControl x:Class="YourNamespace.AudioPlayerView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:YourNamespace">
<UserControl.DataContext>
<local:AudioPlayer/>
</UserControl.DataContext>
<StackPanel>
<Label Name="lbl_bind" Content="{Binding CurrentTrack.Title}"></Label>
<Button Name="btn" Click="btn_Click" Height="20" ></Button>
</StackPanel>
</UserControl>
我建议避免命名控件,除非您实际上是在编写代码(对于MVVM来说,这应该是不必要的)。我还建议从“Click”处理程序切换到“Command”处理程序,并使用类似“DelegateCommand”的方法来处理按钮事件 这个类不是静态的。你为什么要谈论静态类?你说的“scorporate”是什么意思?它是静态的,因为这个私有的静态AudioPlayer实例=newAudioPlayer();不是静态的类是Track,但在这一点上,我对如何处理mvvm有点困惑。我将编写一个处理AudioPlayer的类,并删除该类中更改的所有NotifyPropertyChanged,因为“CurrentTrack”是模型,而不是ModelView,它是一个静态字段,而不是一个静态类。您的应用程序是您的ViewModels,而不是视图,因此静态
DataContext
表示静态应用程序。您最好在应用程序首次启动时创建一个新的AudioPlayer
实例,并将其设置为应用程序的DataContext
。在应用程序中可以有静态组件,但不要使整个应用程序都是静态的。Rachel,你的意思是这样的吗?