WPF Setup software interface background for MediaElement and play video

Source: Internet
Author: User

In our common software interface design we often set the background of the software for SolidColorBrush or Linercolorbrush, RadialGradientBrush and other series of color brush as the background, Sometimes we also use ImageBrush to add images as the background of the interface, in addition to commonly used DrawingBrush and the visualbrush that need to be summarized today, which we are relatively easy to achieve, So if we want to design the interface of the software into an animation or simply play a video as the background, this is a huge improvement for the whole software.

First, let's take a look at the background property, which is explained on MSDN: Gets or sets the Brush used to populate the area between the control's borders. Its type is: type: System.Windows.Media.Brush, so we can use a control or property with a Brush property to populate it as a background.

Let's start by looking at the design of the foreground style:

<window x:class= "Testbackgroundworker.mainwindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:ui=" clr-namespace:x.ui;assembly=x .    UI "xmlns:local=" Clr-namespace:testbackgroundworker "title=" MainWindow "height=" 681 "width=" > <Window.Resources> <style targettype= "Local:backgroundplayer" > <setter property= "Template                        "> <Setter.Value> <controltemplate targettype=" Local:backgroundplayer "> <mediaelement x:name= "Media" stretch= "Fill" ></MediaElement> </cont roltemplate> </Setter.Value> </Setter> </Style> </window.resou rces> <Grid> <Grid.Background> <VisualBrush> <visualbrush.visu                           Al>             <local:backgroundplayer source= "~/images/bg.avi" ></local:BackgroundPlayer> </vi sualbrush.visual> </VisualBrush> </Grid.Background> </Grid></Window>

Here we use the VisualBrush brush, and then add our custom style to the VisualBrush visual, this is a very important brush, if we have a clear inheritance of WPF, We will find that almost all controls inherit from the top-level base class of visual, so almost all control can be used as VisualBrush visual, so the background property of the grid is very rich, Here we define a Backgroundplayer custom control and change its control template.

So let's focus on how this custom control is defined in the background:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows;usingSystem.Windows.Controls;namespacetestbackgroundworker{ Public classBackgroundPlayer:System.Windows.Controls.Control {StaticBackgroundplayer () {Defaultstylekeyproperty.overridemetadata (typeof(Backgroundplayer),NewFrameworkpropertymetadata (typeof(Backgroundplayer))); }         Public stringSource {Get{return(string) GetValue (sourceproperty); }            Set{SetValue (sourceproperty, value);} }               Public Static ReadOnlyDependencyProperty sourceproperty =Dependencyproperty.register ("Source",typeof(string),typeof(Backgroundplayer),NewFrameworkpropertymetadata ("", (A, b) = ={backgroundplayer bp= A asBackgroundplayer; if(BP. Player! =NULL) {BP. Player.source=NewUri (B.newvalue.tostring (). Replace ("~", AppDomain.CurrentDomain.BaseDirectory), Urikind.relativeorabsolute);        }                           })); PrivateMediaElement _player;  PublicMediaElement Player {Get{return_player;} Set{_player =value;} }         Public Override voidOnApplyTemplate () {Player= GetTemplateChild ("Media") asMediaElement; if(NULL==Player)Throw NewArgumentNullException ("Media"); Player.loadedbehavior=mediastate.manual; player.mediaended+=player_mediaended; player.mediaopened+=player_mediaopened; Player.mediafailed+=player_mediafailed; player.loaded+=player_loaded; if(!string. IsNullOrEmpty (Source)) {Player.source=NewUri (Source.replace ("~", AppDomain.CurrentDomain.BaseDirectory), Urikind.relativeorabsolute);            Player.play (); }            Base.        OnApplyTemplate (); }        voidPlayer_loaded (Objectsender, RoutedEventArgs e) {        }        voidPlayer_mediafailed (Objectsender, Exceptionroutedeventargs e) {        }        voidPlayer_mediaopened (Objectsender, RoutedEventArgs e) {            //Player.play ();        }        voidPlayer_mediaended (Objectsender, RoutedEventArgs e) {player.position= Timespan.frommilliseconds (1);        Player.play (); }    }}

Here our custom controls are inherited from System.Windows.Controls.Control, and we look at the relevant code and do further analysis. First we must add a default static constructor for the current class, which is very important, and it changes the default control style.

Static Backgroundplayer ()        {            defaultstylekeyproperty.overridemetadata (typeof (Backgroundplayer), new Frameworkpropertymetadata (typeof (Backgroundplayer)));        }

Next we need to define some default dependency properties for the custom control, first of all: the Source property, and since we define the property of control as MediaElement, we must set the relevant property for this MediaElement, Here we define a callback function for this source property when the property is changed, which triggers the callback function when it is assigned to the source property for the first time in XAML, so we can often use the callback function to do something, which is very useful.

In addition, we also need to set some common properties for MediaElement, such as what to do after the current chip source is completed.

Here we do the related operations by overloading the Onapplytemplate method of the base class, which we must understand when we learn about WPF, to overload these common virtual methods to do our work. Of course, it also requires us to accumulate constantly.

Let's take a look at onapplytemplate. This virtual method is to complete what kind of operation, by overriding Onapplytemplate (), you can get the child control in the template by Gettemplatechild method, However, there is a problem with the order of execution of the onapplytemplate, when the constructor of the class executes, the Onapplytemplate method is not executed immediately, but a certain amount of time is deferred. And if this custom control is placed in the application's project, if visibility is hidden, it will not execute the Onapplytemplate method, which we need to pay attention to, It is a very effective way to add events to our program by overriding the Onapplytemplate method to get the MediaElement object.

Finally post a corresponding look at the effect of the animation (Star style map)

The complete video is a moving picture, here just cut out a few photos, normal play when the entire surface is moving, the above article is only simple to analyze, for reference only.

WPF Setup software interface background for MediaElement and play video

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.