[C#][WPF] MVVM Command Binding을 통해 버튼 상태 제어하기

ESOLOGY·2021년 9월 10일
0
post-thumbnail

🙋‍♀️계획

  1. Click 버튼을 누르면 TextBox 입력창에 입력한 단어를 하단 TextBlock에 나타내주기
  2. TextBox Text에 변화가 있으면 TextBlock Clear 해주기
  3. "disabled"라는 단어가 입력되면 Click 버튼이 비활성화 되도록

MainWindow.xaml

<Window x:Class="ButtonExcuteChange.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:vm="clr-namespace:ButtonExcuteChange.ViewModel"
        xmlns:local="clr-namespace:ButtonExcuteChange"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
  <!-- ViewModel 연결-->
  <Window.DataContext>
    <vm:MainWindowViewModel x:Name="ViewModel"/>
  </Window.DataContext>
  <Grid>
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical">
      <!-- 실시간으로 입력 값의 변화를 알 수 있도록 UpdateSourceTrigger = PropertyChanged로 설정 -->
      <TextBox Text="{Binding txtTextBox, UpdateSourceTrigger = PropertyChanged}" Width="100" Margin="0,0,0,20">
        <TextBox.InputBindings>
          <KeyBinding Key="Enter" Command="{Binding EnterKeyPressCommand}"/>
        </TextBox.InputBindings>
      </TextBox>
      <!-- Button Command 지정-->
      <Button Content="Click" Command="{Binding ButtonClickCommand}" Margin="0,0,0,20"/>
      <TextBlock Text="{Binding txtTextBlock}" Foreground="DarkSlateBlue"/>
    </StackPanel>
  </Grid>
</Window>

MainWindowViewModel.cs

using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace ButtonExcuteChange.ViewModel
{
  class MainWindowViewModel : ObservableObject 
  {
    private string _txtTextBox;
    public string txtTextBox
    {
      get => this._txtTextBox;
      set
      {
        SetProperty(ref this._txtTextBox, value);
        TextChange();
      }
    }

    private string _txtTextBlock;
    public string txtTextBlock
    {
      get => this._txtTextBlock;
      set { SetProperty(ref this._txtTextBlock, value); }
    }

    //버튼의 활성화와 관련된 property
    private bool isDisabled;
    public bool IsDisabled
    {
      get => this.isDisabled;
      set
      {
        SetProperty(ref this.isDisabled, value);
        //상태가 바뀌면 CanExecute 속성이 알 수 있도록 연결
        (ButtonClickCommand as RelayCommand).NotifyCanExecuteChanged();
      }
    }

    //버튼 Command의 CanExecute 속성. true-> 버튼 활성화, false-> 버튼 비활성화
    private bool CanExecuteButtonClick()
    {
      return !this.isDisabled;
    }
    
    //Textbox 입력을 감지하는 Command
    public ICommand TextChangeCommand { get; }
    //Button Click과 관련된 Command
    public ICommand ButtonClickCommand { get; }
    //Textbox에서 Enter를 누르면 Button Click을 하도록 하는 Command
    public ICommand EnterKeyPressCommand { get; }

    public MainWindowViewModel()
    {
      TextChangeCommand = new RelayCommand(TextChange);
      ButtonClickCommand = new RelayCommand(ButtonClick, CanExecuteButtonClick);
      EnterKeyPressCommand = new RelayCommand(EnterKeyPress);
    }

    private void TextChange()
    {
      if (txtTextBox.ToLower() == "disabled")
      {
        IsDisabled = true;
      }
      else
      {
        IsDisabled = false;
      }

      txtTextBlock = null;
    }

    private void ButtonClick()
    {
      txtTextBlock = _txtTextBox;
    }

    private void EnterKeyPress()
    {
      if (!isDisabled)
      {
        ButtonClick();
      }
    }
  }
}
profile
👩‍💻

0개의 댓글