Aidanpraid
Aidanpraid

Reputation: 112

Conflict in using SizeToContent=widthandHeight and WindowStartupLocation in WPF

We're stuck on an issue about the appropriate use of SizeToContent=WidthandHeight and WindowStartupLocation=CenterScreen in WPF. After resizing, our window has strange black border and it is not at the center.

Upvotes: 1

Views: 1217

Answers (3)

JanH
JanH

Reputation: 117

Approved solution worked for me but I could sometimes spot the black border for a microsecond. Was playing little bit and found this fixing it.

DialogWindow.xaml

<Window ...
        WindowStartupLocation="CenterOwner"
        SizeToContent="WidthAndHeight" 
        SnapsToDevicePixels="True"
        ...

DialogWindow.xaml.cs

protected override void OnActivated(EventArgs e)
{
    InvalidateMeasure();
    base.OnActivated(e);
}

Upvotes: 0

Aidanpraid
Aidanpraid

Reputation: 112

We have solved it with this class. You should use it instead of common Window.

public class CustomizableChromeWindow : Window, INotifyPropertyChanged
{
    protected override void OnStateChanged(EventArgs e)
    {
        base.OnStateChanged(e);
        OnPropertyChanged("CaptionButtonMargin");
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        HandleSizeToContent();
    }
    private void HandleSizeToContent()
    {
        if (this.SizeToContent == SizeToContent.Manual)
            return;

        var previosTopXPosition = this.Left;
        var previosTopYPosition = this.Top;
        var previosWidth = this.MaxWidth;
        var previosHeight = this.MaxHeight;

        var previousWindowStartupLocation = this.WindowStartupLocation;
        var previousSizeToContent = SizeToContent;
        SizeToContent = SizeToContent.Manual;
        Dispatcher.BeginInvoke(
        DispatcherPriority.Loaded,
        (Action)(() =>
        {
            this.SizeToContent = previousSizeToContent;

            this.WindowStartupLocation = WindowStartupLocation.Manual;

            this.Left = previosTopXPosition + (previosWidth - this.ActualWidth)/2;
            this.Top = previosTopYPosition + (previosHeight - this.ActualHeight) / 2;
            this.WindowStartupLocation = previousWindowStartupLocation;
        }));
    }
    public Thickness CaptionButtonMargin
    {
        get
        {
            return new Thickness(0, 0, 0, 0);
        }
    }

    #region INotifyPropertyChanged
    private void OnPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
}

Upvotes: 1

Michael M&#252;ller
Michael M&#252;ller

Reputation: 21

The code does not work until MaxWith and MaxHeight is given. To fix this, I used the RestoreBounds instead:

var previosWidth = this.RestoreBounds.Width;
var previosHeight = this.RestoreBounds.Height;

Upvotes: 1

Related Questions