WPF:SizeChanged 总是被触发

时间:2021-06-28 13:33:37

标签: wpf wpf-controls

我使用 ResponsiveGrid 制作动态页面并设置 SizeChanged 事件以更改按钮的位置。但是 SizeChanged 总是被触发使窗口闪烁,并且 SizeChanged 事件无法停止,这是我在 .cs 中的代码

 private void Condition_SizeChanged(object sender, EventArgs e)
        {
            if (ActualWidth > 1480)
            {
                Col1.Height = new GridLength(100.0, GridUnitType.Star);
                Col2.Height = new GridLength(1.0, GridUnitType.Star);
                Row1.Width = new GridLength(5.0, GridUnitType.Star);
                Row2.Width = new GridLength(1.0, GridUnitType.Star);

                CommonButtonSearch.SetValue(Grid.ColumnProperty, 1);
                CommonButtonSearch.SetValue(Grid.RowProperty, 0);

                CommonButtonSearch.Margin = new Thickness(30, (ActualHeight - 32) / 2, 0, (ActualHeight - 32) / 2);

            }
            else
            {
                Row1.Width = new GridLength(100.0, GridUnitType.Star);
                Row2.Width = new GridLength(1.0, GridUnitType.Star);
                Col1.Height = new GridLength(5.0, GridUnitType.Star);
                Col2.Height = new GridLength(1.0, GridUnitType.Star);

                CommonButtonSearch.SetValue(Grid.ColumnProperty, 0);
                CommonButtonSearch.SetValue(Grid.RowProperty, 1);

                CommonButtonSearch.Margin = new Thickness((ActualWidth - 120) / 2, 30, (ActualWidth - 120) / 2, 30);
            }
        }

1 个答案:

答案 0 :(得分:0)

当您在代码中设置行和列的 WidthHeight 属性时,只要更改了大小,就会引发该事件。

您可能希望使用变量来“暂停”在执行代码时引发的事件:

private bool _handle = true;
private void Condition_SizeChanged(object sender, EventArgs e)
{
    if (!_handle)
        return;

    _handle = false;
    if (ActualWidth > 1480)
    {
        Col1.Height = new GridLength(100.0, GridUnitType.Star);
        Col2.Height = new GridLength(1.0, GridUnitType.Star);
        Row1.Width = new GridLength(5.0, GridUnitType.Star);
        Row2.Width = new GridLength(1.0, GridUnitType.Star);

        CommonButtonSearch.SetValue(Grid.ColumnProperty, 1);
        CommonButtonSearch.SetValue(Grid.RowProperty, 0);

        CommonButtonSearch.Margin = new Thickness(30, (ActualHeight - 32) / 2, 0, (ActualHeight - 32) / 2);

    }
    else
    {
        Row1.Width = new GridLength(100.0, GridUnitType.Star);
        Row2.Width = new GridLength(1.0, GridUnitType.Star);
        Col1.Height = new GridLength(5.0, GridUnitType.Star);
        Col2.Height = new GridLength(1.0, GridUnitType.Star);

        CommonButtonSearch.SetValue(Grid.ColumnProperty, 0);
        CommonButtonSearch.SetValue(Grid.RowProperty, 1);

        CommonButtonSearch.Margin = new Thickness((ActualWidth - 120) / 2, 30, (ActualWidth - 120) / 2, 30);
    }
    _handle = true;
}