从ViewModel执行UserControl readonly ICommand

时间:2012-02-29 18:45:45

标签: c# wpf mvvm user-controls

我有专门的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; }
}

Class diagram

问题是: SlideshowViewModel如何执行此控件的PlayCommand ?有最好的做法吗?

1 个答案:

答案 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
      }

}