[WPF] MVVM 패턴 Button 컨트롤 선택된 버튼 배경색상 변경하기

안녕하세요.

 

오늘은 WPF에서 MVVM 패턴을 이용하여 Button 컨트롤 다루는 방법에 대해서 알려 드리려고 합니다.

 

그 중에서도 여러 개의 Button 컨트롤 중에서 사용자가 특정 Button 컨트롤이 선택이 되면 해당 버튼이 선택되었다는 것을 Color로 사용자에게 보여주는 방법에 대해서 보여 드리려고 합니다.

 

제가 독학으로 공부하면서 작성한 부분이라서..많이 부족한 내용들이 많을 테지만..참고만 해주시면 좋겠습니다!ㅎㅎ

 

그럼 바로 예제 코드를 통해서 어떻게 특정 Button 컨트롤의 색상을 표시하는지 보여드리겠습니다.

 

 

MainWindow.xaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<Window x:Class="WpfApp4.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:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
 
    <StackPanel>
        <Button Content="Add TextBox" Command="{Binding TestCommand}"/>
        <ItemsControl x:Name="MyItems" ItemsSource="{Binding ButtonCollection}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button x:Name="MyButton" Content="{Binding Path=Name, Mode=TwoWay, 
                        UpdateSourceTrigger=PropertyChanged}"
                            FontWeight="Bold"
                            FontSize="18"
                            Margin="10"
                            Width="100"
                            Background="{Binding SelectedColor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                            Command="{Binding ElementName=MyItems,
                        Path=DataContext.SubButtonCommand}"
                            CommandParameter="{Binding Name}">
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
 
</Window>
 
cs

 

MainWIndowViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;
using System.Windows.Media;
 
namespace WpfApp4
{
    public class MainWindowViewModel
    {
        public ObservableCollection<Buttons> _buttonCollections;
        public ObservableCollection<Buttons> ButtonCollection
        {
            get { return _buttonCollections; }
            set
            {
                if (_buttonCollections != null)
                    _buttonCollections = value;
            }
        }
 
        public ICommand TestCommand { get; private set; }
        public ICommand SubButtonCommand { get; private set; }
 
        public MainWindowViewModel()
        {
            Init();
        }
 
        private void Init()
        {
            _buttonCollections = new ObservableCollection<Buttons>();
            TestCommand = new RelayCommand<object>(CommandMethod);
            SubButtonCommand = new RelayCommand<object>(SubCommandMethod);
        }
 
        private void CommandMethod(object parameter)
        {
            for (int idx = 0; idx < 4; idx++)
            {
                ButtonCollection.Add(new Buttons { Name = $"Button {idx}", SelectedColor = Brushes.Transparent });
            }
        }
 
        private void SubCommandMethod(object parameter)
        {
            ButtonColorClear();
 
            var result = ButtonCollection.Where(x => x.Name.Equals(parameter.ToString()))
                                         .SingleOrDefault();
 
            if (result != null)
            {
                result.SelectedColor = Brushes.LightBlue;
            }
        }
 
        private void ButtonColorClear()
        {
            for (int idx = 0; idx < ButtonCollection.Count; idx++)
            {
                ButtonCollection[idx].SelectedColor = Brushes.Transparent;
            }
        }
    }
 
    public class Buttons : INotifyPropertyChanged
    {
        public string Name { get; set; }
 
        private Brush _selectedColor = Brushes.Transparent;
        public Brush SelectedColor
        {
            get
            {
                return _selectedColor;
            }
            set
            {
                if (_selectedColor != null)
                    _selectedColor = value;
 
                OnPropertyChanged("SelectedColor");
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));
        }
    }
}
 
cs

 

RelayCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;
using System.Windows.Input;
 
namespace WpfApp4
{
    public class RelayCommand<T> : ICommand
    {
        readonly Action<T> _execute = null;
        readonly Predicate<T> _canExecute = null;
 
        public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }
 
        public bool CanExecute(object parameter)
        {
            return _canExecute?.Invoke((T)parameter) ?? true;
        }
 
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
 
        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }
    }
}
 
cs

 

실행 결과

위와 같이 제가 선택한 Button 컨트롤의 Backgroud 색상이 변경되어 표시되는 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY