我有一个这样写的类
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"是你的"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,这应该是大多数不必要的)。我还建议从"单击"处理程序切换到"命令"处理程序,并使用类似于"委托命令"来处理按钮事件。