我有专门的UserControl
来播放名为PlayerView
的媒体内容。
该控件具有自己的命令(只读,不是由客户提供的。)
public partial class PlayerView
{
public PlayerView()
{
InitializeComponent();
PlayCommand = new RelayCommand(() =>
{
// Play some media: audio/video.
});
}
...
#region PlayCommand property
private static readonly DependencyPropertyKey PlayCommandPropertyKey = DependencyProperty.RegisterReadOnly(
"PlayCommand",
typeof(ICommand),
typeof(PlayerView),
new PropertyMetadata());
public static readonly DependencyProperty PlayCommandProperty = PlayCommandPropertyKey.DependencyProperty;
public ICommand PlayCommand
{
get { return (ICommand)GetValue(PlayCommandProperty); }
private set { SetValue(PlayCommandPropertyKey, value); }
}
#endregion
...
}
控件的播放命令在XAML中运行良好:
<Controls:PlayerView x:Name="PlayerView" />
<Button Command="{Binding ElementName=PlayerView, Path=PlayCommand, Mode=OneWay}" Content="Play" />
但是目前,我正在实现幻灯片放映功能,我想从 ViewModel 执行控件的播放命令。
public class SlideshowViewModel : ViewModelBase
{
// Stores collection of audio/video clips to be played by the PlayerView.
// Assume that this ViewModel should invoke PlayerView PlayCommand.
}
public class MainViewModel : ViewModelBase
{
// Stores a lot of stuff.
public SlideshowViewModel Slideshow { get; }
}
问题是: SlideshowViewModel如何执行此控件的PlayCommand ?有最好的做法吗?
答案 0 :(得分:1)
如果我正确理解您的问题,ViewModel应该包含Command的实现,而不是View。这将是一个更真实的MVVM实现,然后VM可以在必要时从内部调用该命令。
编辑:
回答你的问题,
public partial class PlayerView : IHaveAPlayCommand
{
public PlayerView()
{
this.DataContext = new ViewModel(this);
}
}
public class ViewModel
{
IHaveAPlayCommand view;
public ViewModel(IHaveAPlayCommand view)
{
this.view = view
}
}