Close the application from the user control.

I have MainWindow in my application. MainWindow places the UserControl in its ContentControl (I call it MainPage). MainPage goes to the hosts of another UserControl, which contains all kinds of controls (KiviPage) on it.

I am trying to connect to a database in MainPage and upload a file to KiviPage. If either of the two operations fails (connecting to the database or downloading the file), I must exit the application. This means that I have to exit the application with custom controls.

What is the best way to do this?

+4
source share
2 answers

I think you can implement this action through the attached DependencyProperty . Something like this (this is 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> 

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

You can put any behavior into DependencyProperty , which is accessible only through code and call it XAML:

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

In addition, you can access it directly through the behavior code:

 ProgramBehaviours.SetShutdown(SomeControl, Value); 

Or from XAML without a condition:

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

Just call "Shutdown" from the code located behind the user control:

 Application.Current.Shutdown(); 
+3
source

Source: https://habr.com/ru/post/1491236/


All Articles