简体   繁体   中英

C#/WPF Resize Window to MediaElement's Original Content size

I have a Window which a dynamically size with it's content (MediaElement).

For this I use a Window with the Attribute SizeToContent="WidthAndHeight" . My MediaElement is set like this Stretch="Uniform" StretchDirection="DownOnly" .

With those Settings the Window will be as big as the original size of the MediaElement Control. But Stretching is set to DownOnly and I'd like the possibility to make the window bigger. But when i set the Attribute StretchDirection to Both, the Window will be Maximized when I load another Movie with MediaElement.

I would like that the Window has the Size of the MediaElement, but when I make the Window bigger I want that the MediaElement is getting bigger too.

Thanks for your help in advance!

This is the WPF Window

<base:ContentWindow x:Class="ExplorerExtension.WindowsMediaWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:base="clr-namespace:ExplorerExtension" ShowActivated="False" 
WindowStyle="None" ResizeMode="CanResizeWithGrip" SizeToContent="WidthAndHeight">
    <Grid>
        <MediaElement x:Name="MediaEL" MediaOpened="MediaEL_MediaOpened"
                  LoadedBehavior="Manual" Stretch="Uniform" StretchDirection="DownOnly"/>
    </Grid>
</base:ContentWindow>

And the Code

    public WindowsMediaWindow()
    {
        InitializeComponent();
        MediaEL.Source = new Uri("---");
    }

窗户的图片

Note: All Videos have different sizes, so I can't set a fixed Width or Height

I am sorry I could not identify the reason of your problem. But here is a solution of it.

Solution:

Set StretchDirection="DownOnly" by the start, but as you change the size of the window, set it to UpOnly .

Technical Description:

To do this, you'll have to subscribe to the SizeChanged event of the Window . But the problem is, this event also fires at the startup of the application. So you'll have to subscribe to that event after loading the window.

So, first of all subscribe to the Loaded event of the window and in that event handler, subscribe to the SizeChanged event:

XAML (in window tag):

Loaded="Window_Loaded"

C#:

private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
    MediaEL.StretchDirection = StretchDirection.UpOnly;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.SizeChanged += Window_SizeChanged;
}

You can also refer to this article, it defines StretchDirection with very nice examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM