Playing a sound in Silverlight with MediaElement and Caliburn Micro

谁说胖子不能爱 提交于 2019-12-06 08:12:51

问题


How can I play an MP3 in Silverlight using Caliburn Micro?

The MediaElement's "play()" method needs to be executed based on a boolean variable in the ViewModel.

Thanks in advance!


回答1:


Use an IResult. sample code Edit: based on a Boolean value, if you describe the scenario of this I can alter the sample.

View:

<Grid>
        <MediaElement AutoPlay="False"
                      Source="../Assests/Kalimba.mp3"></MediaElement>
        <Button x:Name="Play"
                Content="Play"
                Height="50"
                Width="150" />
    </Grid>

ViewModel:

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;
        }
    }
}


来源:https://stackoverflow.com/questions/7446850/playing-a-sound-in-silverlight-with-mediaelement-and-caliburn-micro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!