首页 > 解决方案 > WPF:SizeChanged 总是被解雇

问题描述

我使用 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);
            }
        }

标签: wpfwpf-controls

解决方案


当您在代码中设置行和列的Width和属性时,可能会在更改大小时引发该事件。Height

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

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;
}

推荐阅读