我有一个以这种方式写的课
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。 怎么做?
答案 0 :(得分:0)
假设'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”之类的东西来处理按钮事件。