다음을 통해 공유


방법: 명령 사용

다음 예제에서는 Windows Presentation Foundation (WPF)에서 명령을 사용하는 방법을 보여 줍니다. 이 예제에서는 RoutedCommandButton에 연결하고 CommandBinding을 만들고 RoutedCommand를 구현하는 이벤트 처리기를 만드는 방법을 보여 줍니다. 명령에 대한 자세한 내용은 명령 개요를 참조하십시오.

예제

첫 번째 코드 섹션에서는 ButtonStackPanel로 구성된 user interface (UI)를 만들고 RoutedCommand에 명령 처리기를 연결하는 CommandBinding을 만듭니다.

ButtonCommand 속성을 Close 명령에 연결합니다.

CommandBinding을 루트 WindowCommandBindingCollection에 추가합니다. ExecutedCanExecute 이벤트 처리기를 이 바인딩에 연결한 후 Close 명령에 연결합니다.

CommandBinding이 없으면 명령 논리는 없고 명령을 호출하는 메커니즘만 있게 됩니다. Button을 클릭하면 명령 대상에서 PreviewExecuted RoutedEvent가 발생한 후 Executed RoutedEvent가 발생합니다. 이러한 이벤트는 해당 특정 명령에 대한 CommandBinding을 찾아 요소 트리를 이동합니다. RoutedEvent는 요소 트리를 터널링 및 버블링하므로 CommandBinding을 배치할 위치를 신중하게 선택해야 합니다. CommandBinding이 명령 대상의 형제 대상에 있거나 이 RoutedEvent의 경로에 없는 다른 노드에 있으면 CommandBinding이 액세스되지 않습니다.

<Window x:Class="WCSamples.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="CloseCommand"
    Name="RootWindow"
    >
  <Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close"
                    Executed="CloseCommandHandler"
                    CanExecute="CanExecuteHandler"
                    />
  </Window.CommandBindings>
  <StackPanel Name="MainStackPanel">
    <Button Command="ApplicationCommands.Close" 
            Content="Close File" />
  </StackPanel>
</Window>
            ' Create ui elements.
            Dim CloseCmdStackPanel As New StackPanel()
            Dim CloseCmdButton As New Button()
            CloseCmdStackPanel.Children.Add(CloseCmdButton)

            ' Set Button's properties.
            CloseCmdButton.Content = "Close File"
            CloseCmdButton.Command = ApplicationCommands.Close

            ' Create the CommandBinding.
            Dim CloseCommandBinding As New CommandBinding(ApplicationCommands.Close, AddressOf CloseCommandHandler, AddressOf CanExecuteHandler)

            ' Add the CommandBinding to the root Window.
            RootWindow.CommandBindings.Add(CloseCommandBinding)
// Create ui elements.
StackPanel CloseCmdStackPanel = new StackPanel();
Button CloseCmdButton = new Button();
CloseCmdStackPanel.Children.Add(CloseCmdButton);

// Set Button's properties.
CloseCmdButton.Content = "Close File";
CloseCmdButton.Command = ApplicationCommands.Close;

// Create the CommandBinding.
CommandBinding CloseCommandBinding = new CommandBinding(
    ApplicationCommands.Close, CloseCommandHandler, CanExecuteHandler);

// Add the CommandBinding to the root Window.
RootWindow.CommandBindings.Add(CloseCommandBinding);

다음 코드 섹션에서는 ExecutedCanExecute 이벤트 처리기를 구현합니다.

Executed 처리기는 열려 있는 파일을 닫기 위해 메서드를 호출합니다. CanExecute 처리기는 파일이 열려 있는지 여부를 확인하기 위해 메서드를 호출합니다. 파일이 열려 있으면 CanExecute가 true로 설정되고, 그렇지 않으면 false로 설정됩니다.

        ' Executed event handler.
        Private Sub CloseCommandHandler(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
            ' Calls a method to close the file and release resources.
            CloseFile()
        End Sub

        ' CanExecute event handler.
        Private Sub CanExecuteHandler(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
            ' Call a method to determine if there is a file open.
            ' If there is a file open, then set CanExecute to true.
            If IsFileOpened() Then
                e.CanExecute = True
            ' if there is not a file open, then set CanExecute to false.
            Else
                e.CanExecute = False
            End If
        End Sub
// Executed event handler.
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    // Calls a method to close the file and release resources.
    CloseFile();
}

// CanExecute event handler.
private void CanExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
{
    // Call a method to determine if there is a file open.
    // If there is a file open, then set CanExecute to true.
    if (IsFileOpened())
    {
        e.CanExecute = true;
    }
    // if there is not a file open, then set CanExecute to false.
    else
    {
        e.CanExecute = false;
    }
}

참고 항목

개념

명령 개요