退出用户Control的应用程序

时间:2013-07-13 04:31:56

标签: wpf xaml wpf-controls

我的应用程序中有一个MainWindow。 MainWindow在其ContentControl中托管UserControl(我称之为MainPage)。 MainPage进入另一个UserControl,其中包含各种控件(KiviPage)。

我正在尝试连接到MainPage中的数据库并在KiviPage中加载文件。如果两个操作中的任何一个失败(连接到数据库或文件加载),我必须退出该应用程序。这意味着我必须从用户控件退出应用程序。

最好的办法是什么?

2 个答案:

答案 0 :(得分:3)

只需拨打用户控件的"Shutdown" from code behind

Application.Current.Shutdown();

答案 1 :(得分:1)

我认为,您可以通过附加的DependencyProperty实施此操作。类似的东西(这是一个简单的工作示例):

XAML

<Window x:Class="ShutdownAppHelp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ShutdownAppHelp"
    Title="MainWindow" Height="350" Width="525">

<Window.Resources>
    <Style TargetType="{x:Type CheckBox}">
        <Style.Triggers>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="local:ProgramBehaviours.Shutdown" Value="True" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

    <Grid>
        <CheckBox Content=" Shutdown" IsChecked="False" />
    </Grid>
</Window>

Code behind

namespace ShutdownAppHelp
{    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public static class ProgramBehaviours
    {
        // Shutdown program
        public static void SetShutdown(DependencyObject target, bool value)
        {
            target.SetValue(ShutdownProperty, value);
        }

        public static readonly DependencyProperty ShutdownProperty =
                                                  DependencyProperty.RegisterAttached("Shutdown",
                                                  typeof(bool),
                                                  typeof(ProgramBehaviours),
                                                  new UIPropertyMetadata(false, OnShutdown));

        // Here call function in UIPropertyMetadata()
        private static void OnShutdown(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is bool && ((bool)e.NewValue))
            {
                Application.Current.Shutdown();             
            }
        }
    }
}

您可以在DependencyProperty中放置任何类型的行为,只能通过代码将其称为XAML:

<DataTrigger Binding="{Binding ElementName=SomeControl, Path=Tag}" Value="Shutdown">
    <Setter Property="local:ProgramBehaviours.Shutdown" Value="True" />
</DataTrigger>

此外,您可以通过行为代码直接访问它:

ProgramBehaviours.SetShutdown(SomeControl, Value);

或者没有条件的XAML:

<SomeControl local:ProgramBehaviours.SetShutdown="True" ... />