Megosztás a következőn keresztül:


Útmutató: Az ICommandSource implementálása

Ez a példa bemutatja, hogyan hozhat létre parancsforrást ICommandSourceimplementálásával. A parancsforrás olyan objektum, amely tudja, hogyan hívhat meg parancsokat. A ICommandSource felület három tagot tesz elérhetővé:

  • Command: a meghívandó parancs.
  • CommandParameter: felhasználó által definiált adattípus, amelyet a parancs forrásától a parancsot kezelő metódusnak ad át.
  • CommandTarget: az objektum, amelyen a parancs végrehajtása folyamatban van.

Ebben a példában létrejön egy osztály, amely örökli a Slider vezérlőt, és implementálja a ICommandSource felületet.

példa

A WPF számos osztályt biztosít, amelyek ICommandSourceimplementálnak , például Button, MenuItemés Hyperlink. A parancsforrás határozza meg, hogyan hívja meg a parancsot. Ezek az osztályok parancsot hívnak meg, amikor rákattintanak, és csak akkor válnak parancsforrássá, ha be van állítva Command tulajdonságuk.

Ebben a példában a csúszka áthelyezésekor vagy pontosabban a Value tulajdonság módosításakor fogja meghívni a parancsot.

Az osztálydefiníció a következő:

public class CommandSlider : Slider, ICommandSource
{
    public CommandSlider() : base()
    {
    }
Public Class CommandSlider
    Inherits Slider
    Implements ICommandSource
    Public Sub New()
        MyBase.New()

    End Sub

A következő lépés a ICommandSource tagok implementálása. Ebben a példában a tulajdonságok DependencyProperty objektumként vannak implementálva. Ez lehetővé teszi, hogy a tulajdonságok adatkötést használjanak. A DependencyProperty osztályról további információt a Függőség tulajdonságainak áttekintésecímű témakörben talál. Az adatkötésről további információt az Adatkötés áttekintésecímű cikkben talál.

Itt csak a Command tulajdonság látható.

// Make Command a dependency property so it can use databinding.
public static readonly DependencyProperty CommandProperty =
    DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(CommandSlider),
        new PropertyMetadata((ICommand)null,
        new PropertyChangedCallback(CommandChanged)));

public ICommand Command
{
    get
    {
        return (ICommand)GetValue(CommandProperty);
    }
    set
    {
        SetValue(CommandProperty, value);
    }
}
' Make Command a dependency property so it can use databinding.
Public Shared ReadOnly CommandProperty As DependencyProperty =
    DependencyProperty.Register("Command", GetType(ICommand),
        GetType(CommandSlider),
        New PropertyMetadata(CType(Nothing, ICommand),
            New PropertyChangedCallback(AddressOf CommandChanged)))

Public ReadOnly Property Command1() As ICommand Implements ICommandSource.Command
    Get
        Return CType(GetValue(CommandProperty), ICommand)
    End Get
End Property

Public Property Command() As ICommand
    Get
        Return CType(GetValue(CommandProperty), ICommand)
    End Get
    Set(ByVal value As ICommand)
        SetValue(CommandProperty, value)
    End Set
End Property

Az alábbi DependencyProperty változásvisszahívás:

// Command dependency property change callback.
private static void CommandChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    CommandSlider cs = (CommandSlider)d;
    cs.HookUpCommand((ICommand)e.OldValue,(ICommand)e.NewValue);
}
' Command dependency property change callback.
Private Shared Sub CommandChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    Dim cs As CommandSlider = CType(d, CommandSlider)
    cs.HookUpCommand(CType(e.OldValue, ICommand), CType(e.NewValue, ICommand))
End Sub

A következő lépés a parancsforráshoz társított parancs hozzáadása és eltávolítása. A Command tulajdonságot nem lehet egyszerűen felülírni egy új parancs hozzáadásakor, mert az előző parancshoz társított eseménykezelőket el kell távolítani, ha volt ilyen.

// Add a new command to the Command Property.
private void HookUpCommand(ICommand oldCommand, ICommand newCommand)
{
    // If oldCommand is not null, then we need to remove the handlers.
    if (oldCommand != null)
    {
        RemoveCommand(oldCommand, newCommand);
    }
    AddCommand(oldCommand, newCommand);
}

// Remove an old command from the Command Property.
private void RemoveCommand(ICommand oldCommand, ICommand newCommand)
{
    EventHandler handler = CanExecuteChanged;
    oldCommand.CanExecuteChanged -= handler;
}

// Add the command.
private void AddCommand(ICommand oldCommand, ICommand newCommand)
{
    EventHandler handler = new EventHandler(CanExecuteChanged);
    canExecuteChangedHandler = handler;
    if (newCommand != null)
    {
        newCommand.CanExecuteChanged += canExecuteChangedHandler;
    }
}
' Add a new command to the Command Property.
Private Sub HookUpCommand(ByVal oldCommand As ICommand, ByVal newCommand As ICommand)
    ' If oldCommand is not null, then we need to remove the handlers.
    If oldCommand IsNot Nothing Then
        RemoveCommand(oldCommand, newCommand)
    End If
    AddCommand(oldCommand, newCommand)
End Sub

' Remove an old command from the Command Property.
Private Sub RemoveCommand(ByVal oldCommand As ICommand, ByVal newCommand As ICommand)
    Dim handler As EventHandler = AddressOf CanExecuteChanged
    RemoveHandler oldCommand.CanExecuteChanged, handler
End Sub

' Add the command.
Private Sub AddCommand(ByVal oldCommand As ICommand, ByVal newCommand As ICommand)
    Dim handler As New EventHandler(AddressOf CanExecuteChanged)
    canExecuteChangedHandler = handler
    If newCommand IsNot Nothing Then
        AddHandler newCommand.CanExecuteChanged, canExecuteChangedHandler
    End If
End Sub

A következő lépés az CanExecuteChanged kezelő logikájának létrehozása.

A CanExecuteChanged esemény értesíti a parancs forrását arról, hogy a parancs végrehajtása az aktuális parancscélon megváltozott. Amikor egy parancsforrás megkapja ezt az eseményt, általában meghívja a parancs CanExecute metódusát. Ha a parancs nem hajtható végre az aktuális parancscélon, a parancsforrás általában letiltja magát. Ha a parancs végrehajtható az aktuális parancscélon, a parancsforrás általában engedélyezi magát.

private void CanExecuteChanged(object sender, EventArgs e)
{

    if (this.Command != null)
    {
        RoutedCommand command = this.Command as RoutedCommand;

        // If a RoutedCommand.
        if (command != null)
        {
            if (command.CanExecute(CommandParameter, CommandTarget))
            {
                this.IsEnabled = true;
            }
            else
            {
                this.IsEnabled = false;
            }
        }
        // If a not RoutedCommand.
        else
        {
            if (Command.CanExecute(CommandParameter))
            {
                this.IsEnabled = true;
            }
            else
            {
                this.IsEnabled = false;
            }
        }
    }
}
Private Sub CanExecuteChanged(ByVal sender As Object, ByVal e As EventArgs)

    If Me.Command IsNot Nothing Then
        Dim command As RoutedCommand = TryCast(Me.Command, RoutedCommand)

        ' If a RoutedCommand.
        If command IsNot Nothing Then
            If command.CanExecute(CommandParameter, CommandTarget) Then
                Me.IsEnabled = True
            Else
                Me.IsEnabled = False
            End If
            ' If a not RoutedCommand.
        Else
            If Me.Command.CanExecute(CommandParameter) Then
                Me.IsEnabled = True
            Else
                Me.IsEnabled = False
            End If
        End If
    End If
End Sub

Az utolsó lépés a Execute metódus. Ha a parancs egy RoutedCommand, a rendszer meghívja a RoutedCommandExecute metódust; ellenkező esetben a ICommandExecute metódus lesz meghívva.

// If Command is defined, moving the slider will invoke the command;
// Otherwise, the slider will behave normally.
protected override void OnValueChanged(double oldValue, double newValue)
{
    base.OnValueChanged(oldValue, newValue);

    if (this.Command != null)
    {
        RoutedCommand command = Command as RoutedCommand;

        if (command != null)
        {
            command.Execute(CommandParameter, CommandTarget);
        }
        else
        {
            ((ICommand)Command).Execute(CommandParameter);
        }
    }
}
' If Command is defined, moving the slider will invoke the command;
' Otherwise, the slider will behave normally.
Protected Overrides Sub OnValueChanged(ByVal oldValue As Double, ByVal newValue As Double)
    MyBase.OnValueChanged(oldValue, newValue)

    If Me.Command IsNot Nothing Then
        Dim command As RoutedCommand = TryCast(Me.Command, RoutedCommand)

        If command IsNot Nothing Then
            command.Execute(CommandParameter, CommandTarget)
        Else
            CType(Me.Command, ICommand).Execute(CommandParameter)
        End If
    End If
End Sub

Lásd még