Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing layout update

Tags:

wpf

How to force the layout measurements update?

I have simplified layout I am problem with; when you click the button first time you get one measurement and on the second click different one.

   private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var w = mywindow.ActualWidth;
        gridx.Width = w;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        btn3.Width = 100;
        var w = mywindow.ActualWidth;
        gridx.Width = w - btn3.Width;
        InvalidateArrange();
        InvalidateMeasure();

        MessageBox.Show(btn1.ActualWidth.ToString());
    }

Window

<Window x:Class="resizet.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" Name="mywindow">

        <DockPanel HorizontalAlignment="Stretch" LastChildFill="False">
            <Grid HorizontalAlignment="Stretch" DockPanel.Dock="Left" Name="gridx">
                <Button HorizontalAlignment="Stretch" Content="btn in grid" Click="Button_Click" />
            </Grid>
        <Button Name="btn2" Content="btn2" Width="0" DockPanel.Dock="Right" HorizontalAlignment="Left"></Button>
        </DockPanel>
</Window>
like image 627
David Daks Avatar asked Jan 13 '23 06:01

David Daks


1 Answers

This fixes the problem:

btn3.Width = 100;    
btn3.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
var w = mywindow.ActualWidth;
gridx.Width = w - btn3.Width;

with additional

private static Action EmptyDelegate = delegate() { };
like image 95
Daniel Avatar answered Jan 22 '23 12:01

Daniel