从用户控件退出应用程序 [英] Quit application from a user Control
问题描述
我的应用程序中有一个 MainWindow.MainWindow 在其 ContentControl 中承载一个 UserControl(我称之为 MainPage).MainPage 托管另一个 UserControl,其中包含各种控件 (KiviPage).
I have a MainWindow in my application. The MainWindow hosts a UserControl in its ContentControl(I call this MainPage). MainPage goes onto hosts another UserControl which contains all sorts of controls on it (KiviPage).
我正在尝试连接到 MainPage 中的数据库并在 KiviPage 中加载文件.如果这两个操作中的任何一个失败(连接到数据库或文件加载),我必须退出应用程序.这意味着我必须从用户控件中退出应用程序.
I am trying to connect to a database in MainPage and load a file in the KiviPage. If any of the two operations fail (connection to database or file loading) I have to quit the application. Which means I have to quit the application from the user controls.
最好的方法是什么?
推荐答案
我认为,您可以通过附加的 DependencyProperty
来实现此操作.类似的东西(这是一个简单的工作示例):
I think, you may implement this action through a attached DependencyProperty
. Something like that (it's a simple work example):
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>
背后的代码
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:
You can put any kind of behavior in DependencyProperty
, which is available only through the code and call it a XAML:
<DataTrigger Binding="{Binding ElementName=SomeControl, Path=Tag}" Value="Shutdown">
<Setter Property="local:ProgramBehaviours.Shutdown" Value="True" />
</DataTrigger>
另外,你可以通过行为代码直接访问它:
Also, you can access it directly through the code of behavior:
ProgramBehaviours.SetShutdown(SomeControl, Value);
或从 XAML 无条件:
Or from XAML without condition:
<SomeControl local:ProgramBehaviours.SetShutdown="True" ... />
这篇关于从用户控件退出应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!