Popup in windows phone 8

2019-02-19 11:28发布

问题:

I want to show a popup with media element as one control. When user clicks on the button, then I have to show this popup. And when user clicks on the back button of the device then the popup should be closed.

Please help me how to do this in windows phone 8 application.

回答1:

Popup with MediaElement (view is name of PhoneApplicationPage)

<Popup
    x:Name="popup">

    <Grid
        Background="{StaticResource PhoneChromeBrush}"
        Height="{Binding Path=ActualHeight, ElementName=view}"
        Width="{Binding Path=ActualWidth, ElementName=view}">

        <MediaElement />

    </Grid>

</Popup>

Application Bar

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>

        <shell:ApplicationBarIconButton
            Click="ShowPopup"
            IconUri="/Icons/show.png"
            Text="show" />

    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Code behind

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    if (this.popup.IsOpen)
    {
        this.popup.IsOpen = false; 
        e.Cancel = true;
    }

    base.OnBackKeyPress(e);
}


private void ShowPopup(object sender, EventArgs e)
{
    this.popup.IsOpen = true;
}


回答2:

You have to create a Popup control & have to set your media element as it's Child Property.And to handle Back Key press use OnBackKeyPress overriden event.

Please see below sample.

    private Popup _popup;

    private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Grid g=new Grid {Height = 400,Width = 480,Background =new SolidColorBrush(Colors.Green)};
        Rectangle r = new Rectangle
            {
                Height = 50,
                Width=50,
                Fill = new SolidColorBrush(Colors.Red),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            };
        g.Children.Add(r);
        _popup = new Popup()
           {
               Height = 400,
               Width = 480,
               IsOpen = true,
               Child = g
           };          
    }

    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        if (_popup != null)
        {
            if (_popup.IsOpen)
            {
                e.Cancel = true;
                _popup.IsOpen = false;
            }
        }
    }


回答3:

When you press back key, You should check is popup open? If popup open then prevent the back key action. So override OnBackKeyPress() like this:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    if (this.popup.IsOpen)
    {
        this.popup.IsOpen = false; 
        e.Cancel = true;
    }

    base.OnBackKeyPress(e);
}