[WPF] Global gültiges CloseCommand

Cappaja

Erfahrenes Mitglied
Hallo,

ich habe eine Anwendung mit relativ vielen Dialogen und insofern viele this.Close() Aufrufe. Um das Ganze übersichtlicher zu gestalten möchte ich gerne ein Klasse "CloseCommand" erstellen welche ohne die Nutzung der CodeBehind Datei auskommt sondern lediglich über ein CommandBinding im XAML Code.
Frage: Wie löse ich das am elegantesten?

Grüße Cappaja
 
Eine mögliche Lösung würde so aussehen:

Code:
 public partial class MainWindow : Window
    {
        public static readonly RoutedCommand CloseCommand =  new RoutedCommand("Close", typeof(MainWindow));

        public MainWindow()
        {
            InitializeComponent();
                       
            var command1 = new CommandBinding(CloseCommand, FireClose, null);
            this.CommandBindings.Add(command1);
        }

        private void FireClose(object sender, ExecutedRoutedEventArgs args)
        {
            Close();
        }
    }

Um das Command dann zu Binden brauchst du folgendes:

Code:
<UserControl x:Class="CloseCommandTest.Control"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local ="clr-namespace:CloseCommandTest"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Width="100" Height="30" Content="Close" Command="{x:Static local:MainWindow.CloseCommand}"  />
            
    </Grid>
</UserControl>
 
Zurück