如何使用Caliburn Micro在Silverlight中播放MP3?
MediaElement的“play()”方法需要根据ViewModel中的布尔变量执行。
提前致谢!
答案 0 :(得分:4)
使用IResult。 sample code 编辑:基于布尔值,如果你描述了这个场景,我可以改变样本。
查看:
<Grid>
<MediaElement AutoPlay="False"
Source="../Assests/Kalimba.mp3"></MediaElement>
<Button x:Name="Play"
Content="Play"
Height="50"
Width="150" />
</Grid>
视图模型:
public class MediaViewModel : Screen
{
public MediaViewModel()
{
DisplayName = "Media Sample";
}
public IEnumerable<IResult> Play()
{
var result = new PlayMediaResult();
yield return result;
}
}
PlayMediaResult:
public class PlayMediaResult : IResult
{
public void Execute(ActionExecutionContext context)
{
var view = context.View as FrameworkElement;
var mediaElement = FindVisualChild<MediaElement>(view);
if (mediaElement != null)
{
mediaElement.Play();
Completed(this, new ResultCompletionEventArgs {});
}
Completed(this, new ResultCompletionEventArgs {});
}
public event EventHandler<ResultCompletionEventArgs> Completed;
public static TChildItem FindVisualChild<TChildItem>(DependencyObject obj)
where TChildItem : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is TChildItem)
return (TChildItem) child;
var childOfChild = FindVisualChild<TChildItem>(child);
if (childOfChild != null)
return childOfChild;
}
return null;
}
}
}