【问题标题】:Previous User Controls stay active after changing ContenControl content更改 ContentControl 内容后,以前的用户控件保持活动状态
【发布时间】:2017-10-27 11:35:32
【问题描述】:

在我的WPF 应用程序中,我有一个主窗口和两个用户控件,我使用以下代码在我的用户控件之间进行更改:

    private void SwitchControls(MyButton btnCurrent)
    {
        switch (btnCurrent.Name)
        {
            case "btnLine":
                {
                    winLine win = new winLine();
                    ccContent.Content = win;
                }
                break;
            case "btnHistory":
                {
                    winHistory win = new winHistory();
                    ccContent.Content = win;
                }
                break;
        }
    }

ccContent 是我主窗口中的 ContentControl。 winLine 和 winHistory 是我的两个用户控件。在我的winLine 中,我有一个每 5 秒计时一次的计时器,每当我切换到以前的用户控件中的 winHistory 计时器时,计时器就会一直计时。在切换用户控件之前,我尝试做ccContent.Content = null;,但它没有帮助。

如何禁用或删除以前的用户控制并只保留一个活动的?我希望我的问题很清楚。

【问题讨论】:

  • 在用新的东西替换之前检查Content 属性。
  • 这就是我想要做的。如何清除Content?
  • 可能最简单的解决方案可能是在用户控件中使用计时器简单地订阅Unloaded 事件并在那里停止计时器。

标签: c# wpf user-controls contentcontrol


【解决方案1】:

在重置Content 属性之前停止并处置计时器。您可以通过尝试使用 as 运算符将 Content 属性的值转换为 winLine 来做到这一点:

private void SwitchControls(MyButton btnCurrent)
{
    winLine current = ccContent.Content as winLine;
    if (current != null && current.Timer != null)
    {
        current.Timer.Stop();
        current.Timer.Dispose();
    }

    switch (btnCurrent.Name)
    {
        case "btnLine":
            {
                winLine win = new winLine();
                ccContent.Content = win;
            }
            break;
        case "btnHistory":
            {
                winHistory win = new winHistory();
                ccContent.Content = win;
            }
            break;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多