BlackCoin's Corner

In diesem Blog dreht es sich zu 90 % um den Themenbereich C# .Net

Commands

Um in WPF mit Commands zu Arbeiten, gibt es unterschiedliche Möglichkeiten, an dieser Stelle möchte ich nun, 3 dieser Möglichkeiten Vorstellen.

 

1. Das Command durch Implementation des Interface ICommand

using System; 
using System.Windows.Input; 


namespace WpfApplication15 
{ 
    public class DummyCommmand: ICommand 
    { 
        public bool CanExecute(object parameter) 
        { 
            // Darf ich etwas machen 
        } 


        public event EventHandler CanExecuteChanged; 


        public void Execute(object parameter) 
        { 
            // Mache etwas 
        } 
    } 
}

Dieses einfache Command kann dann, sobald er zB. in der Resource eines Windows definiert wurde, den einzelnen Command Properties, der jeweiligen Controls zugewiesen werden.

<Window x:Class="WpfApplication15.MainWindow" 
        xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>" 
        xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>" 
        xmlns:local="clr-namespace:WpfApplication15" 
        Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
        <local:DummyCommmand x:Key="dummyCommand"/> 
    </Window.Resources> 
    <Grid> 
        <Button Content="Push" Command="{StaticResource dummyCommand}"/> 
    </Grid> 
</Window>

Auf diese Weise können die Commands, innerhalb der gesamten Anwendung Verwendung finden. Je nach Ausprägung dieser Klasse, können auch unterschiedliche Properties Definiert werden, die das Control auf eine bestimmte Art und weise beeinflussen. zB. könnte ein Property Tooltip Implementiert werden, das dann an das jeweilige Steuerelement gebunden werden kann. So hätte man dann Anwendungsweit, immer ein nur Control, dass identisch aussieht sondern auch immer die gleiche Aktion ausführt.

 

2. Das Command in der Business Logik

Da das .Net Framework, uns bereits zwei, im im Namespace ‘System.Windows.Input’, vorimplementierte Commands, mit auf den Weg gibt, lassen sich damit auch sehr schnell, Commands innerhalb der Business Logik anlegen. Die beiden vorimplementierten Commands, sind zum einen das RoutedCommand und das RoutedUICommand, der unterschied liegt eigentlich nur in dem Property Text vom RoutedUICommand, dass sobald es an ein Control gebunden wird, deren Beschriftung beeinflussen kann.

using System.Windows.Input; 


namespace WpfApplication15 
{ 
    public class DummyBL 
    { 
        public CommandBinding DummyCommand { get; set; } 


        public DummyBL() 
        { 
            DummyCommand = new CommandBinding(new RoutedUICommand("Dummy", "DummyCommand", typeof(DummyBL))); 


            DummyCommand.CanExecute += (sender, ex) => ex.CanExecute = true; 
            DummyCommand.Executed += DummyCommand_Executed; 
        } 


        void DummyCommand_Executed(object sender, ExecutedRoutedEventArgs e) 
        { 
            //mache etwas 
        } 
    } 
}

using System.Windows; 


namespace WpfApplication15 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
        DummyBL dummyBl; 


        public MainWindow() 
        { 
            dummyBl = new DummyBL(); 
            InitializeComponent(); 


            this.CommandBindings.Add(dummyBl.DummyCommand); 


            this.DataContext = dummyBl; 
        } 
    } 
}

<Window x:Class="WpfApplication15.MainWindow" 
        xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>" 
        xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>" 
        Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
        <Button Content="Push" Command="{Binding DummyCommand.Command}"/> 
    </Grid> 
</Window>

Mit dieser Implementierung, kann man ein Command definieren, dass sehr stark mit der Business Logik verknüpft ist und nur durch Databinding an die jeweilige Sicht und letztendlich auch an das Steuerelement gebunden wird.

 

3. eine eigene Klasse zur Gruppierung von Commands

Bei dieser Command Implementierung, erstellt man sich eine Sammlung aus logisch zusammenhängenden Commands eine Commandgruppe. Diese Gruppen können immer dann zum Einsatz kommen, wenn sich die Logik, hinter dem ausführendem Command, immer wieder ändert, jedoch zB. der Shortcut, Text oder möglicherweise auch Tooltip Anwendungsweit identisch sein soll.

Als erstes die Command Gruppe

using System.Windows.Input; 
using System.Collections.Generic; 


namespace App.Commands 
{ 
    public class Commands 
    { 
        #region Fields (1) 


        // Fields 
        private static Dictionary<CommandId, RoutedUICommand> _internalCommands = new Dictionary<CommandId, RoutedUICommand>(); 


        #endregion Fields 


        #region Enums (1) 


        private enum CommandId : int 
        { 
            Save = 0, 
        } 


        #endregion Enums 


        #region Properties (1) 


        public static RoutedUICommand Save { get { return BuildCommand(CommandId.Save); } } 


        #endregion Properties 


        #region Methods (3) 


        // Private Methods (3) 


        private static RoutedUICommand BuildCommand(CommandId idCommand) 
        { 
            if (!_internalCommands.ContainsKey(idCommand)) 
                _internalCommands.Add(idCommand, new RoutedUICommand(GetUIText(idCommand), GetPropertyName(idCommand), typeof(Commands), GetShortKey(idCommand))); 


            return _internalCommands[idCommand]; 
        } 


        private static string GetPropertyName(CommandId commandId) 
        { 
            return commandId.ToString("g"); 
        } 


        private static string GetUIText(CommandId commandId) 
        { 
            switch ((commandId)) 
            { 
                case CommandId.Save: 
                    return "Speichern"; 
                default: 
                    return ""; 
            } 


        } 


        private static InputGestureCollection GetShortKey(CommandId commandId) 
        { 
            InputGestureCollection igc = new InputGestureCollection(); 


            switch ((commandId)) 
            { 
                case CommandId.Save: 
                    igc.Add(new KeyGesture(Key.S, ModifierKeys.Control)); 
                    break; 
            } 
            return igc; 
        } 


        #endregion Methods 
    } 
}

<Window x:Class="WpfApplication15.MainWindow" 
        xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>" 
        xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>" 
        xmlns:command="clr-namespace:App" 
        Title="MainWindow" Height="350" Width="525"> 
    <Window.CommandBindings> 
        <CommandBinding Command="command:Commands.Save" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed"/> 
    </Window.CommandBindings> 
    <Grid> 
        <Button Content="{Binding Path=Command.Text, RelativeSource={RelativeSource Self}}" Command="command:Commands.Save"/> 
    </Grid> 
</Window>

using System.Windows; 


namespace WpfApplication15 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
        private void CommandBinding_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e) 
        { 
            e.CanExecute = true; 
        } 


        private void CommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) 
        { 
            MessageBox.Show("Dieser Command wurde ausgeführt"); 
        } 
    } 
}

 

Auf diesem Wege erhalten wir Logische Command Gruppen, die jeweilige Implementierung kommt innerhalb der einzelnen Comands kann dann von Fall zu Fall unterschiedlich implementiert werden.


Posted: Nov 22 2009, 03:18 von Lars Schmitt | mit 1 comment(s)
Abgelegt unter:

Kommentare

dotnet-kicks.de sagte:

Sie wurden gekickt (eine gute Sache) - Trackback von dotnet-kicks.de

# November 22, 2009 10:02
Kommentar abgeben

(verpflichtend) 

(verpflichtend) 

(optional)

(verpflichtend)