我想说链接中的代码不违反 MVVM 模式...它使用代码隐藏,这在 MVVM 中不建议使用,但它不违反。
话虽如此,该代码在可重用的 UserControl 或自定义控件中会更好,通过事件、命令或 DependencyProperty 返回快照,以便您可以将其绑定到您的 ViewModel。
但总的来说,这更多的是一种良好做法,而不是 MVVM 要求。
<UserControl x:Class="SnapShots.SnapShotMediaViewer"
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="MediaViewer">
<StackPanel>
<MediaElement x:Name="media" Stretch="Fill" Height="200" Width="300">
<MediaElement.Triggers>
<EventTrigger RoutedEvent="MediaElement.Loaded">
<BeginStoryboard>
<Storyboard>
<MediaTimeline Source="thomasOnBoard.wmv"
RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</MediaElement.Triggers>
</MediaElement>
<Button Click="Button_Click" Content="Snapshot"/>
</StackPanel>
</UserControl>
例如,在代码隐藏中,通过事件公开快照。或者,如果您想在视图中完全避免代码隐藏或 EventTriggers,请使用 DependencyProperty。
public partial class SnapShotMediaViewer : UserControl
{
public static readonly DependencyPropertyKey SnapshotPropertyKey =
DependencyProperty.RegisterReadOnly("Snapshot", typeof(BitmapSource),
typeof(SnapShotMediaViewer), new PropertyMetadata(null));
public static readonly DependencyProperty SnapshotProperty =
SnapshotPropertyKey.DependencyProperty;
public BitmapSource Snapshot
{
get
{
return (BitmapSource)GetValue(SnapshotProperty);
}
private set
{
SetValue(SnapshotProperty, value);
}
}
void Button_Click(object sender, RoutedEventArgs e)
{
Size dpi = new Size(96,96);
RenderTargetBitmap bmp =
new RenderTargetBitmap(300, 200,
dpi.Width, dpi.Height, PixelFormats.Pbgra32);
bmp.Render(media);
Snapshot = bmp;
}
}
然后只需将此控件添加到您的视图并创建一个绑定到Snapshot 属性。