지금 예제는Command Bindings 와 CommandExecute 와 CommandExecute 를 간단하게 사용해보자.~

Command를사용하는 이유?

http://msdn.microsoft.com/ko-kr/library/ms752308(v=VS.90).aspx

명령의 정의


WPF의 명령 시스템은 RoutedCommandRoutedEvent를 기반으로 합니다. 명령은 반드시 RoutedCommand일 필요가 없으며 단순히 ICommand를 구현할 수도 있지만 이 개요에서는 주로 RoutedCommand 모델에 중점을 두어 설명합니다.

명령은 작업의 의미 체계 및 출처를 해당 논리와 구분한다는 점에서 단추에 연결된 간단한 이벤트 처리기와 다릅니다. 이와 같은 특징 때문에 서로 다른 여러 소스가 동일한 명령 논리를 호출할 수 있으며 명령 논리를 여러 대상에 대해 사용자 지정할 수 있습니다.

이러한 명령의 예로 여러 응용 프로그램에서 볼 수 있는 복사, 잘라내기, 붙여넣기 등의 편집 작업이 있습니다. 명령의 의미 체계는 응용 프로그램과 클래스 전체에서 일관되지만 작업 논리는 작업 대상 개체마다 다릅니다. Ctrl+X 키 조합은 텍스트 클래스, 이미지 클래스 및 웹 브라우저에서 잘라내기 명령을 호출하지만 잘라내기 작업을 수행하는 실제 논리는 명령을 호출한 소스가 아니라 잘라내기가 발생하는 개체 또는 응용 프로그램에 따라 정의됩니다. 예를 들어 텍스트 개체는 선택한 텍스트를 잘라내서 클립보드에 복사하는 반면 이미지 개체는 선택한 이미지를 잘라내지만 두 클래스 모두에서 동일한 명령 소스인 KeyGesture 또는 ToolBar 단추를 사용하여 명령을 호출할 수 있습니다.

 

실행된 모습

image

100미만 일때 버튼 비활성화

image

 

XAML

    <Grid>
        <Button Content="Button" Margin="192,146,163,93" Name="Btn" />
        <TextBox Height="40" HorizontalAlignment="Left" Margin="192,100,0,0" Name="textBox1" VerticalAlignment="Top" Width="148" Text="100" FontSize="28" />
        <Label Content="입력값이 100 이상일때만 아래버튼 활성화" Height="43" HorizontalAlignment="Left" Margin="12,28,0,0" Name="label1" VerticalAlignment="Top" FontSize="24" />
    </Grid>

 

Cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static RoutedCommand MyCommand = new RoutedCommand();


        public MainWindow()
        {
            InitializeComponent();
            CommandBinding cb = new CommandBinding(MyCommand,
       MyCommandExecute, MyCommandCanExecute);

            this.CommandBindings.Add(cb);
            this.Btn.Command = MyCommand; //버튼에다가 커멘트 연결중…
        }
//CommandCanExecute요기서  CommandExecute 를 실행할수 있는지 검사 ㅋ
        private void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textBox1.Text))
            {
                if (int.Parse(this.textBox1.Text) >= 100)
                {
                    e.CanExecute = true;
                }
                else
                {
                    e.CanExecute = false;
                }
            }
            else {
                e.CanExecute = false;
            }
        }

        private void MyCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("My Command!");
         
        }
    }
}

+ Recent posts