다음을 통해 공유


방법: 명령 사용

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

예제

코드의 첫 번째 섹션은 ButtonStackPanel로 구성된 UI(사용자 인터페이스)를 만들고, 명령 처리기를 RoutedCommand와 연결하는 CommandBinding을 만듭니다.

ButtonCommand 속성은 Close 명령과 연결되어 있습니다.

CommandBinding은 루트 WindowCommandBindingCollection에 추가됩니다. ExecutedCanExecute 이벤트 처리기는 이 바인딩에 연결되어 있으며 Close 명령에 연결됩니다.

CommandBinding이 없으면 명령 논리는 없으며 명령을 호출하는 메커니즘만 있습니다. Button을 클릭하면 PreviewExecutedRoutedEvent가 명령 대상에서 발생한 다음 ExecutedRoutedEvent가 표시됩니다. 이러한 이벤트는 해당 특정 명령에 대한 CommandBinding을 찾는 요소 트리를 트래버스합니다. RoutedEvent 터널과 버블이 요소 트리를 통과하므로 CommandBinding이 배치되는 위치에 주의해야 합니다. CommandBinding이 명령 대상 형제의 또는 RoutedEvent의 경로에 있지 않은 다른 노드에 있는 경우 CommandBinding에 액세스할 수 없습니다.

<Window x:Class="WCSamples.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://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.
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);
' 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)

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

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

// 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;
    }
}
' 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

참고 항목